Sub topic 7
Handing Large Workloads to Batch Apex
This chapter assumes you can write a Schedulable class, read a cron expression, and call System.schedule. It also assumes you know SOQL, DML, and the basic governor limits. Here you will learn why a scheduled job should often start a Batch Apex job instead of doing the work itself.
Why a scheduled job should not do heavy work
A scheduled class runs in one transaction. That transaction has the usual asynchronous governor limits: a cap on SOQL rows returned, a cap on DML rows, and a cap on CPU time. The first example in this tutorial, EscalateStaleCases, avoids the limits by adding LIMIT 200 to its query. That works for a small queue of cases. It fails silently when thousands of records qualify, because the extra records are simply never processed.
Batch Apex solves this. A batch job splits the records into chunks called batches. Each batch runs in its own transaction with a fresh set of governor limits. The scheduled class then has one task: start the batch job.
The division of labor
- The Schedulable class decides when the work starts. It holds no business logic beyond starting the job.
- The Batchable class decides what work happens. It queries the records and processes them chunk by chunk.
A worked example
The following code deletes closed tasks older than a year. The batch class and the schedulable class are shown together.
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);
}
}The three batch methods each have a distinct role:
startruns once. It returns aDatabase.QueryLocator, which can cover up to 50 million records.executeruns once per chunk. Thescopelist holds that chunk's records.finishruns once at the end. It is the place for follow-up work such as sending a summary email or starting another job.
The second argument to Database.executeBatch is the scope size, which is the number of records per chunk. The default is 200. Lower it if each record triggers expensive logic, such as callouts or heavy automation, so that each chunk stays within its limits.
Schedule it the same way as any other job:
System.schedule('Nightly task cleanup', '0 0 2 * * ?', new NightlyTaskCleanup());This runs at 2:00 AM every day.
What changes when you use a batch job
Starting a batch from execute is an asynchronous hand-off. The scheduled job finishes as soon as it has queued the batch. This has three consequences.
- The batch does not necessarily start immediately. It joins the flex queue of pending batch jobs, and it runs when system resources are available.
- The scheduled job's
CronTriggerrecord shows only that the schedule fired. To see whether the data was processed, check the batch job inAsyncApexJob, or look at Apex Jobs in Setup. - An unhandled error in a batch
executefails that chunk only. Earlier chunks stay committed, and later chunks still run.
Common mistakes
- Querying in the Schedulable class. Moving the SOQL into
executeand passing the list to the batch uses up the scheduled transaction's limits. Query in the batchstartmethod instead. - Putting business logic in the Schedulable class. This makes the logic hard to reuse and test. Keep the scheduled class to one line of work.
- Forgetting that
executechunks are independent. Do not rely on instance variables to pass data between chunks unless the class also implementsDatabase.Stateful. - Starting a batch from inside a batch
execute. This is not allowed. Chain fromfinishinstead.
Checking the result
After a scheduled run, find the batch job it started:
AsyncApexJob job = [
SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob
WHERE ApexClass.Name = 'ArchiveOldTasksBatch'
ORDER BY CreatedDate DESC
LIMIT 1
];
System.debug(job.Status + ': ' + job.JobItemsProcessed + '/' + job.TotalJobItems);NumberOfErrors counts failed chunks, not failed records.
Exercise
A scheduled class runs a query with LIMIT 200 and updates the results. The org now has 50,000 matching records each night. What change fixes this, and what does the Schedulable class do afterward?
Show answer
Move the query into a Batchable class's start method, which returns a Database.QueryLocator. Move the update logic into the batch execute method. The Schedulable class then only calls Database.executeBatch with the batch instance, and optionally a scope size. Each chunk of records runs in its own transaction with fresh governor limits.
Exercise
A scheduled job's CronTrigger shows State = 'COMPLETE' and TimesTriggered = 1, yet no records were processed. Where do you look next?
Show answer
Query AsyncApexJob for the batch class, or open Apex Jobs in Setup. The CronTrigger only records that the schedule fired and started the batch. The batch job's Status, JobItemsProcessed, and NumberOfErrors show whether it ran and whether any chunks failed.