Salesforce Batch Apex 批处理(五)AsyncApexJob情报

2021-11-23 21:41:45 浏览数 (1)

如下,在batch所有方法里边都有【Database.BatchableContext】Object,前边讲的的例子中,都没有用到BC,因为它是用来取得【AsyncApexJob】情报跟踪Job进程的,然后可以及时发送邮件共享信息还可以做成后台log并出力等等。

可以使用getJobId()方法取得AsyncApexJob信息。

代码语言:javascript复制
global Database.QueryLocator start(Database.BatchableContext BC) {
  return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, list<sObject> scope) {

}
global void finish(Database.BatchableContext BC) {

}

AsyncApexJob

项目名 详细

ApexClassId 执行Job的ApexClass的Id,参照先是ApexClass

CompletedDate Job完成日时

CronTriggerId 适用于ScheduledApex,取得关联的定时任务情报,参照先是CronTrigge

ExtendedStatus 处理中发生一个以上的错误时,最初的简单错误可以在这里查看

JobItemsProcessed Job项目数

JobType Job种类,有效值Future,SharingRecalculation,ScheduledApex,

BatchApex,BatchApexWorker,TestRequest,TestWorker,ApexToken,Queueable

NumberOfErrors 失败合计数

Status 状况,有效值Holding,Queued,Preparing,Processing,Aborted,Completed,Failed

TotalJobItems Batch合计数

实装例如下

代码语言:javascript复制
global with sharing class ExampleBatchableContextBatch implements Database.Batchable<sObject>{
    public final String query;
    public final Id toUserId;
    public final Id fromUserId;
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, list<sObject> scope) {
        Savepoint sp = Database.setSavepoint();
        try {
            List<Opportunity> opps = new List<Opportunity>();
            for(sObject item : scope){
                Opportunity opp = (Opportunity)item;
                if(opp.OwnerId == fromUserId){
                    opp.OwnerId=toUserId;
                    opps.add(opp);
                }
            }
            update opps;
        } catch (Exception ex) {
            Database.rollback(sp);
        }
    }
    global void finish(Database.BatchableContext BC) {
        // Get the ID of the AsyncApexJob representing this batch job
        // from Database.BatchableContext.
        // Query the AsyncApexJob object to retrieve the current job's information.
        system.debug('>>>>>>>>>>>>BC.getJobId()::' BC.getJobId());
        AsyncApexJob jobItem = [SELECT Id, ApexClassId, ApexClass.Name, CompletedDate,
                            ExtendedStatus, JobType, MethodName, ParentJobId,Status, NumberOfErrors,
                            JobItemsProcessed,TotalJobItems, CreatedBy.Email
                            FROM AsyncApexJob
                            WHERE Id = :BC.getJobId()];
        system.debug('>>>>>>>>>>>>AsyncApexJob::' jobItem);
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {jobItem.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Sharing Recalculation '   jobItem.Status);
        mail.setPlainTextBody
        ('The batch Apex job processed '   jobItem.TotalJobItems   ' batches with '  jobItem.NumberOfErrors   ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

Batch执行前Opportunity:

Batch执行:

代码语言:javascript复制
Id fromUser = [SELECT Id, Name FROM User WHERE Name = 'System'].Id;
Id toUser = [SELECT Id, Name FROM User WHERE Name = 'logon xiang'].Id;
ExampleBatchableContextBatch reassign = new ExampleBatchableContextBatch();
reassign.query = 'SELECT Id, Name, OwnerId, Owner.Name FROM Opportunity WHERE DeleteFlg__c = true';
reassign.fromUserId = fromUser;
reassign.toUserId = toUser;
ID batchprocessid = Database.executeBatch(reassign);

Batch执行后Opportunity:

AsyncApexJob信息:

AsyncApexJob::AsyncApexJob:{Id=7076g00005cbN89AAE, ApexClassId=01p6g00000SC1W3AAL, CompletedDate=2021-11-23 02:56:24, JobType=BatchApex, Status=Completed, NumberOfErrors=0, JobItemsProcessed=1, TotalJobItems=1, CreatedById=0056g000001OqErAAK}

邮件详细:

0 人点赞