Sub topic 12
Running batches on a schedule
A batch job started by hand runs once. Most recurring work, such as nightly cleanups, weekly recalculations, or syncing data after business hours, needs to start by itself. This chapter covers how to start a batch job from a schedule, how to read a cron expression, and where scheduled jobs go wrong.
It assumes you can already write a Database.Batchable class and start it with Database.executeBatch, as covered in earlier chapters.
How scheduling fits with batch jobs
Batch Apex has no built-in schedule. Salesforce provides a separate interface, Schedulable, for that. A schedulable class is a small trigger. At the scheduled time, Salesforce calls its execute method, and that method calls Database.executeBatch. The scheduled job only starts the batch. The batch then runs as its own asynchronous job, with its own chunks and transactions.
Two consequences follow from this design:
- The scheduled job finishes almost immediately. It does not wait for the batch.
- The batch enters the same queue as every other batch job. It can wait, or sit in the Flex Queue, like a job started manually.
The Schedulable class
The class from the Topic Spine looks like this:
public class NightlyAccountRatingJob implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new AccountRatingBatch(), 200);
}
}SchedulableContext has one method, getTriggerId(). It returns the Id of the CronTrigger record that represents this schedule. You can use it to abort or inspect the schedule from inside the job.
Keep the execute method small. It should create the batch instance, pass any parameters through the constructor, and start it. Heavy logic belongs in the batch class, where it gets a fresh set of limits for every chunk.
Registering the schedule
Call System.schedule with a job name, a cron expression, and an instance of the class:
String jobId = System.schedule(
'Nightly account rating',
'0 0 2 * * ?',
new NightlyAccountRatingJob()
);
System.debug('Scheduled as CronTrigger ' + jobId);The call returns the Id of the new CronTrigger. You run this once, for example from Anonymous Apex or a post-deploy script. You do not call it on every run. Running it twice creates a second schedule, or fails if the name is already taken, so check first when a script may run repeatedly:
List<CronTrigger> existing = [
SELECT Id FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly account rating'
];
if (existing.isEmpty()) {
System.schedule('Nightly account rating', '0 0 2 * * ?', new NightlyAccountRatingJob());
}You can also schedule without code. In Setup, open Apex Classes and choose Schedule Apex. That screen offers weekly or monthly options in the UI. Use System.schedule when you need an exact cron expression or want the schedule created as part of a deployment.
Reading a cron expression
Apex cron expressions have six required fields and one optional field, separated by spaces:
Seconds Minutes Hours Day_of_month Month Day_of_week [Year]
Special characters:
*means every value.?means no specific value. It is allowed only in the day-of-month and day-of-week fields. Exactly one of those two fields must be?.,lists values, such as1,15.-gives a range, such as1-5./gives an increment, such as0/15.Lmeans the last day, such as the last day of the month.
| Expression | Meaning |
|---|---|
| `0 0 2 * * ?` | Every day at 02:00 |
| `0 30 6 ? * MON-FRI` | Weekdays at 06:30 |
| `0 0 1 1 * ?` | The first day of each month at 01:00 |
| `0 0 22 L * ?` | The last day of each month at 22:00 |
| `0 0 0/4 * * ?` | Every four hours, starting at midnight |
| `0 0/15 * * * ?` | Every 15 minutes |
The schedule uses the time zone of the user who created it. Check that setting before you rely on "02:00" meaning the same hour as in your documentation.
Limits and behavior to know
- Number of scheduled jobs. An org can have at most 100 scheduled Apex jobs at one time. Leave room for other teams and managed packages.
- Start time is not exact. Salesforce starts the scheduled job when resources are available. It can be late, especially at busy hours such as the top of the hour.
- Batch limits still apply. The batch started from the schedule counts against the limit of five queued or active batch jobs. When that limit is reached, the new job goes to the Flex Queue in Holding status. It can hold up to 100 jobs. Past that,
executeBatchfails. - Running in system mode. Scheduled Apex runs as the user who scheduled it, but without the sharing context of a user session. Declare
with sharingorwithout sharingon the batch class deliberately instead of relying on a default. - Deployment locks. You cannot change or deploy a class that has a pending scheduled job. You get an error along the lines of "This schedulable class has jobs pending or in progress". Abort the schedule, deploy, then schedule again. Deployment scripts should do this automatically.
Do not let runs overlap
If the nightly job takes longer than expected, or you schedule it every 15 minutes, a new run can start while the previous one is still working. Two copies of the same batch can then update the same records, hit row locks, or produce duplicate output.
A scheduled job can check before it starts:
public class NightlyAccountRatingJob implements Schedulable {
public void execute(SchedulableContext sc) {
Integer active = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'AccountRatingBatch'
AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
];
if (active == 0) {
Database.executeBatch(new AccountRatingBatch(), 200);
} else {
System.debug('Previous run still active. Skipping this run.');
}
}
}Monitoring and removing a schedule
The schedule itself is stored in the CronTrigger object. The batch it starts is stored in AsyncApexJob. You need both to see the full picture:
List<CronTrigger> triggers = [
SELECT Id, CronJobDetail.Name, State, CronExpression, PreviousFireTime, NextFireTime, TimesTriggered
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
];
for (CronTrigger ct : triggers) {
System.debug(ct.CronJobDetail.Name + ' next run: ' + ct.NextFireTime);
}Job type '7' is Scheduled Apex. The same list appears in Setup under Scheduled Jobs. To stop a schedule, abort it:
System.abortJob(jobId);Aborting a schedule does not stop a batch that it has already started. Abort that job separately with its own AsyncApexJob Id.
To change a schedule, abort the old one and call System.schedule again with the new expression.
Testing a schedulable class
A scheduled job does not fire inside a test. Test the registration, then test the batch separately, as in the previous chapter:
@IsTest
private class NightlyAccountRatingJobTest {
@IsTest
static void registersSchedule() {
Test.startTest();
String jobId = System.schedule(
'Test nightly rating',
'0 0 2 * * ?',
new NightlyAccountRatingJob()
);
Test.stopTest();
CronTrigger ct = [
SELECT CronExpression, TimesTriggered FROM CronTrigger WHERE Id = :jobId
];
System.assertEquals('0 0 2 * * ?', ct.CronExpression);
System.assertEquals(0, ct.TimesTriggered);
}
}Test.stopTest() forces any asynchronous work that was started, but a future cron time never arrives in a test. To cover the schedulable execute method itself, you can instead call new NightlyAccountRatingJob().execute(null) between startTest and stopTest. The batch then runs when stopTest is called.
Common mistakes
- Using
*in both day fields. One of them must be?. - Scheduling a very frequent job without an overlap check.
- Forgetting that deployment is blocked while the schedule exists.
- Putting query or DML logic in the schedulable class instead of in the batch.
- Expecting
System.scheduleto run the job immediately. It only registers a future run.
Exercise
You need a batch to run on weekdays at 06:30 and not to start if the previous run is still going. Which cron expression do you pass to System.schedule, and what do you check inside the Schedulable class's execute method?
Show answer
Use '0 30 6 ? * MON-FRI'. In execute, query AsyncApexJob for jobs with JobType 'BatchApex', the batch class name, and a Status of Holding, Queued, Preparing, or Processing. Call Database.executeBatch only if the count is zero.
Exercise
A deployment fails with "This schedulable class has jobs pending or in progress". What do you do, and why does aborting the schedule not stop a batch that is already running?
Show answer
Abort the schedule with System.abortJob using the CronTrigger Id, deploy, and then call System.schedule again. The schedule (CronTrigger) and the batch (AsyncApexJob) are separate records. The batch has to be aborted with its own job Id.