Skip to content

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.

apex
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:

apex
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

Build

Execute

Failures

INIT ​

batchable ​

Constructs a new BatchableBuilder instance with the specified batchable job.

Signature

apex
Async batchable(Database.Batchable<Object> job);

Example

apex
Async.batchable(new MyBatchJob());

Build ​

scopeSize ​

Allows setting the scope size for the batch job.

Signature

apex
BatchableBuilder scopeSize(Integer size);

Example

apex
Async.batchable(new MyBatchJob())
	.scopeSize(100);

minutesFromNow ​

Allows scheduling the batch job to run after a specified number of minutes.

Signature

apex
BatchableBuilder minutesFromNow(Integer minutes);

Example

apex
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

apex
SchedulableBuilder asSchedulable();

Example

apex
Async.batchable(new MyBatchJob())
	.asSchedulable();

Execute ​

execute ​

Executes the batch job with the configured options. Returns an Async.Result.

Signature

apex
Async.Result execute();

Example

apex
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.

apex
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

apex
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);
ArgumentWhat it is
batchan instance of the batch class that failed
batchJobIdthe id Database.executeBatch or Async.batchable(...).execute() returned
fieldsToReloadthe fields execute() reads. Use strings for parent paths such as Owner.Email. An empty list means Id only
loaderyour own reload, for anything a field list cannot express

Example

apex
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);
apex
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.