I was learning batch apex and it has three method which is start,execute and finish. Each method has a parameter Database.BatchableContext
.
What is this parameter and why it is being used in all three methods?
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityI was learning batch apex and it has three method which is start,execute and finish. Each method has a parameter Database.BatchableContext
.
What is this parameter and why it is being used in all three methods?
A common use case for this is in the finish()
method to see if any of the execute
transactions had errors
public void finish(BatchableContext bc) {
AsyncApexJob[] jobs = [SELECT Id, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :bc.getJobId()];
if (jobs[0].NumberOfErrors > 0) {..do something, perhaps log/message}
}
For start()
, you might want to abort the job if you detect another batchable already running.
Personally, I've never used that parameter. But it is described in BatchableContext Interface as:
BatchableContext Interface
Represents the parameter type of a batch job method and contains the batch job ID.
Useful I guess if you want to manipulate the job that runs the batchable e.g. to abort it via System.abortJob
.