Batchable API
Apex classes BatchableBuilder.cls and BatchableManager.cls.
New to async jobs? See Standard Apex vs Async Lib for how this maps to a plain Database.executeBatch.
Common BatchJob class example:
Your batch class is a normal Database.Batchable. Async Lib does not change it, so Database.Stateful, Database.QueryLocator, and the start / execute / finish methods all work as usual.
public class AccountCleanupBatch implements Database.Batchable<SObject>, Database.Stateful {
public Integer deletedCount = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account WHERE IsActive__c = false');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
delete scope;
deletedCount += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Deleted ' + deletedCount + ' accounts');
}
}Common Batchable example:
Async.Result result = Async.batchable(new AccountCleanupBatch())
.scopeSize(100)
.execute();
System.debug('Batch job enqueued: ' + result.salesforceJobId);New work over many records?
A ChunkJob gets retry, backoff, a finalizer and a place in the chain. A batch gets none of those, by design. Batch or Chunk? explains the choice and when a batch is still the right tool.
Ready-made cleanup batch
Async Lib ships AsyncResultCleanupBatch for deleting old AsyncResult__c records, with separate retention for failed results and the rest. See AsyncResult Cleanup.
Methods
The following are methods for using Async with Batchable jobs:
INIT
batchable
Constructs a new BatchableBuilder instance with the specified batchable job.
Signature
Async batchable(Database.Batchable<Object> job);Example
Async.batchable(new MyBatchJob());Build
scopeSize
Allows setting the scope size for the batch job.
Signature
BatchableBuilder scopeSize(Integer size);Example
Async.batchable(new MyBatchJob())
.scopeSize(100);minutesFromNow
Allows scheduling the batch job to run after a specified number of minutes.
Signature
BatchableBuilder minutesFromNow(Integer minutes);Example
Async.batchable(new MyBatchJob())
.minutesFromNow(10);asSchedulable
Converts the batch builder to a schedulable builder for cron-based scheduling. See Schedulable API for scheduling options.
Signature
SchedulableBuilder asSchedulable();Example
Async.batchable(new MyBatchJob())
.asSchedulable();Execute
execute
Executes the batch job with the configured options. Returns an Async.Result.
Signature
Async.Result execute();Example
Async.Result result = Async.batchable(new MyBatchJob())
.scopeSize(100)
.execute();Returns result.salesforceJobId containing the Salesforce Job Id.
Failures
A batch that implements Database.RaisesPlatformEvents has every failed scope recorded on AsyncResult__c and reported to your logger, governor limit errors included. The full story is on Batch Failures.
public class MyBatchJob implements Database.Batchable<SObject>, Database.RaisesPlatformEvents {
// start, execute, finish
}requeueBatchFailures
Runs the failed scopes of a batch job again, through the batch's own execute(), as a batch. It needs CreateResult__c on for the batch, because the failed record ids are read from the AsyncResult__c rows.
Signature
Async.RequeueSummary requeueBatchFailures(Object batch, Id batchJobId, List<SObjectField> fieldsToReload);
Async.RequeueSummary requeueBatchFailures(Object batch, Id batchJobId, List<String> fieldsToReload);
Async.RequeueSummary requeueBatchFailures(Object batch, Id batchJobId, Async.BatchRecordLoader loader);| Argument | What it is |
|---|---|
batch | an instance of the batch class that failed |
batchJobId | the id Database.executeBatch or Async.batchable(...).execute() returned |
fieldsToReload | the fields execute() reads. Use strings for parent paths such as Owner.Email. An empty list means Id only |
loader | your own reload, for anything a field list cannot express |
Example
Async.RequeueSummary summary = Async.requeueBatchFailures(
new MyBatchJob(),
failedBatchJobId,
new List<SObjectField>{ Account.Name, Account.Industry }
);
System.debug('Scopes running again: ' + summary.requeued.size());
System.debug('Skipped: ' + summary.skipReasonByResultId);public class AccountLoader implements Async.BatchRecordLoader {
public List<SObject> load(Set<Id> failedRecordIds) {
return [SELECT Id, Name, Owner.Email FROM Account WHERE Id IN :failedRecordIds];
}
}
Async.requeueBatchFailures(new MyBatchJob(), failedBatchJobId, new AccountLoader());A scope that fails again stays open and can be requeued again. Failures in start or finish have no records and are reported in skipReasonByResultId.
