Sub topic 7
Handing Large Workloads to Batch Apex
This chapter assumes you can write Apex classes, run SOQL queries and DML statements, and know the main governor limits. You should also know how to write a Schedulable class and call System.schedule, which earlier chapters covered. Here the scheduled class stops doing the work itself. It becomes a trigger that starts a Batch Apex job.
Why a scheduled class should not do heavy work
The execute method of a Schedulable class runs as one transaction. Everything in it shares one set of governor limits. That includes the total rows returned by SOQL, the number of DML rows, CPU time and heap size.
The first example in this tutorial escalates stale cases. It uses LIMIT 200 so it stays far inside those limits. That works only while the data is small. If 80,000 cases qualify, a single query and a single update will fail. The limit on records processed by DML in one transaction is 10,000, and a single transaction can retrieve at most 50,000 SOQL rows.
Raising the number of rows in one transaction does not fix this. The usual fix is to split the work into slices, and each slice runs in its own transaction with a fresh set of limits. Batch Apex does exactly that.
| Approach | Records per transaction | Fresh limits per slice | Typical use |
|---|---|---|---|
| Work inside `execute` | All of them | No | Small, bounded data sets |
| Scheduled class starts Batch Apex | 1 to 2,000 per batch (default 200) | Yes | Large or growing data sets |
| Scheduled class starts a Queueable | One chunk of your design | Yes, per job | A few steps, callouts, or chained work |
The pattern: the schedule starts the batch
The scheduled class stays small. It decides whether to run and then calls Database.executeBatch. The batch class holds the real logic.
public class ArchiveOldTasksBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id FROM Task WHERE IsClosed = true AND CreatedDate < LAST_N_DAYS:365'
);
}
public void execute(Database.BatchableContext bc, List<Task> scope) {
delete scope;
}
public void finish(Database.BatchableContext bc) {}
}
public class NightlyTaskCleanup implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new ArchiveOldTasksBatch(), 200);
}
}Schedule it as usual:
String cronExp = '0 0 2 * * ?'; // every day at 2:00 AM
System.schedule('Nightly task cleanup', cronExp, new NightlyTaskCleanup());Each time the schedule fires, the following happens:
- The platform runs
NightlyTaskCleanup.executein one short transaction. Database.executeBatchplaces the batch job in the queue and returns the ID of anAsyncApexJobrecord. The scheduled transaction then ends.- When the platform picks up the batch job, it calls
startonce. The query locator defines every record to process. - The platform cuts the result into slices of the scope size (here 200). It calls
executeonce per slice, each in its own transaction. - After the last slice, the platform calls
finishonce.
The Database.executeBatch call and the batch run are separate. The scheduled transaction ends as soon as the job is queued. A failure inside a batch execute does not roll back the earlier slices and does not mark the scheduled job as failed.
Choosing the scope size
The second argument to Database.executeBatch is the scope size. It is the number of records passed to each execute call. The default is 200 and the maximum is 2,000.
- Use a smaller scope (for example 50) when each record triggers heavy work, such as complex triggers, many queries per record, or callouts. A smaller scope keeps each transaction inside its limits.
- Use the default or a larger scope for simple, fast operations. Fewer slices means less overhead.
- If you pass a scope larger than 200 and the batch query is a
QueryLocator, theexecutemethod still receives records in one list. Make sure your logic in that list is bulk-safe.
If your start method returns an Iterable instead of a QueryLocator, the total row limit for the query no longer applies. A QueryLocator can cover up to 50 million records, and that is usually what you want.
Passing parameters and keeping state
A batch class is a normal class, so you can pass values through its constructor. This lets one scheduled class run the same batch with different settings.
Instance variables do not keep their values between execute calls unless the class also implements Database.Stateful. Without it, the platform serializes the class between slices and resets transient state. With it, the class keeps its member variables, which is useful for counters and error lists.
public class ArchiveOldTasksBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer retentionDays;
private Integer deletedCount = 0;
private Integer failedCount = 0;
public ArchiveOldTasksBatch(Integer retentionDays) {
this.retentionDays = retentionDays;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
Date cutoff = Date.today().addDays(-retentionDays);
return Database.getQueryLocator([
SELECT Id FROM Task
WHERE IsClosed = true AND CreatedDate < :cutoff
]);
}
public void execute(Database.BatchableContext bc, List<Task> scope) {
List<Database.DeleteResult> results = Database.delete(scope, false);
for (Database.DeleteResult dr : results) {
if (dr.isSuccess()) {
deletedCount++;
} else {
failedCount++;
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Deleted ' + deletedCount + ' tasks, ' + failedCount + ' failed.');
}
}The scheduled class now builds the batch with a value:
public class NightlyTaskCleanup implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new ArchiveOldTasksBatch(365), 200);
}
}Passing false as the second argument of Database.delete allows partial success. One bad record does not roll back the other 199 records in the slice. Use this when you want to count failures instead of aborting the slice.
Limits on batch jobs started from a schedule
Starting a batch from a schedule adds rules that a plain execute method does not face.
- Five active batch jobs. At most five batch jobs can be queued or active at one time in an org. A sixth job that you start with
Database.executeBatchgoes to the Flex Queue inHoldingstatus, which holds up to 100 jobs. When the Flex Queue is full,executeBatchthrows an exception instead of queuing the job. - Batch from batch. You cannot call
Database.executeBatchfrom inside a batch'sexecutemethod. To run work after a batch, start the next job fromfinish. - Callouts. A scheduled
executemethod cannot make a synchronous callout. A batch class can make callouts if it also implementsDatabase.AllowsCallouts. This is one more reason to hand the work over. - Shared slots. Scheduled jobs and batch jobs from other teams compete for the same five slots. A nightly job that starts at 2:00 AM can wait if other jobs are running.
Because of these limits, the scheduled class should be ready to find that its batch cannot start, or that the previous night's run is still going.
Guarding against overlapping runs
If a nightly batch takes 26 hours, the next schedule firing starts a second copy while the first is still working. Two copies can lock the same records or process them twice. Check AsyncApexJob before you start a new one.
public class NightlyTaskCleanup implements Schedulable {
private static final List<String> ACTIVE_STATUSES =
new List<String>{ 'Holding', 'Queued', 'Preparing', 'Processing' };
public void execute(SchedulableContext sc) {
Integer running = [
SELECT COUNT()
FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'ArchiveOldTasksBatch'
AND Status IN :ACTIVE_STATUSES
];
if (running > 0) {
System.debug('Previous cleanup is still running. Skipping this run.');
return;
}
Database.executeBatch(new ArchiveOldTasksBatch(365), 200);
}
}The guard skips the run and the next firing tries again. If skipping is not acceptable for your process, record the skipped run somewhere visible, such as a custom log object, so someone can see it.
Chaining the next step from finish
The finish method runs once, after all slices. It is the place to start a follow-up job, send a summary email, or write a log record. The BatchableContext gives you the batch job's ID, so you can read the final status.
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob
WHERE Id = :bc.getJobId()
];
System.debug(job.Status + ': ' + job.JobItemsProcessed + '/' + job.TotalJobItems
+ ' slices, ' + job.NumberOfErrors + ' failed');
}Here TotalJobItems counts slices, not records. A job over 1,000 records with a scope of 200 has five items.
Queueable as an alternative
A scheduled class can also start a Queueable job with System.enqueueJob. Choose Queueable when the work is a short sequence of steps, needs complex objects as parameters, or is not driven by one big query. Choose Batch Apex when the work is "every record that matches this query", since the platform handles the slicing, the locking of the query cursor, and the per-slice limits for you.
Testing the hand-off
Test the batch class and the schedule separately. Each test has a clear job.
@IsTest
private class ArchiveOldTasksBatchTest {
@IsTest
static void deletesOldClosedTasks() {
Task oldTask = new Task(Subject = 'Old', Status = 'Completed');
Task newTask = new Task(Subject = 'New', Status = 'Completed');
insert new List<Task>{ oldTask, newTask };
Test.setCreatedDate(oldTask.Id, Datetime.now().addDays(-400));
Test.startTest();
Database.executeBatch(new ArchiveOldTasksBatch(365), 200);
Test.stopTest();
System.assertEquals(0, [SELECT COUNT() FROM Task WHERE Id = :oldTask.Id]);
System.assertEquals(1, [SELECT COUNT() FROM Task WHERE Id = :newTask.Id]);
}
@IsTest
static void nightlyJobIsScheduled() {
String cronExp = '0 0 0 15 3 ? 2099';
Test.startTest();
Id jobId = System.schedule('Test nightly cleanup', cronExp, new NightlyTaskCleanup());
CronTrigger ct = [SELECT CronExpression, TimesTriggered FROM CronTrigger WHERE Id = :jobId];
System.assertEquals(cronExp, ct.CronExpression);
System.assertEquals(0, ct.TimesTriggered);
Test.stopTest();
}
}Points to remember about batch tests:
- Batch jobs started between
Test.startTestandTest.stopTestrun whenTest.stopTestis called. Make your assertions after it. - A test can run only one
executecall for the batch. Keep the test data below the scope size, or the later slices will not run. Test.setCreatedDatelets you set an old creation date, which you cannot do through normal DML.- Keep the test data small. The goal is to prove the logic, not to test volume.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Querying all records in `execute` of the scheduled class | Fails with a row or CPU limit error once data grows | Start a batch and let `start` define the records |
| Starting a batch from a batch `execute` method | Runtime exception | Start follow-up jobs from `finish` |
| Using `Database.Stateful` with large lists | Heap errors, slow slices | Keep only counters and small lists |
| No overlap guard | Two copies work on the same records | Check `AsyncApexJob` before calling `executeBatch` |
| Asserting before `Test.stopTest` | Batch has not run yet, assertion fails | Assert after `Test.stopTest` |
| Scope too large for heavy per-record logic | Limit errors in a slice | Lower the scope size |
Exercise
A scheduled class runs every hour and calls Database.executeBatch(new MyBatch(), 2000). The batch sometimes takes two hours. Name two problems this can cause and one change for each.
Show answer
Problem 1: runs overlap, because a new batch starts every hour while the previous one is still active, so two copies can process the same records. Change: query AsyncApexJob for active jobs of that class (statuses Holding, Queued, Preparing, Processing) and skip the run if one exists. Problem 2: a scope of 2,000 can hit governor limits if each record needs heavy processing, such as triggers or many queries. Change: lower the scope size, for example to 100 or 200, so each slice stays inside its limits.
Exercise
Why does a test that calls Database.executeBatch need its assertions after Test.stopTest(), and why should the test data stay below the scope size?
Show answer
Asynchronous work started inside the test runs only when Test.stopTest() is called, so earlier assertions would see unprocessed data. A test can execute only one execute call of a batch, so records beyond the first scope-size slice would never be processed in the test.