Sub topic 6
Using SchedulableContext to identify the running job
This chapter assumes you can write a basic Schedulable class, run SOQL and DML in Apex, and call System.schedule with a cron expression. If any of those are unfamiliar, review the earlier chapters on the Schedulable interface and on System.schedule first.
What SchedulableContext is
Every execute method in a Schedulable class receives one argument, a SchedulableContext. The interface has a single method:
getTriggerId()returns the ID of theCronTriggerrecord that represents the scheduled job.
This is the only information the platform hands you about the run. It does not carry the cron expression, the job name, the time of the run, or any parameters. All of that is data you can look up, but only if you have the ID.
A CronTrigger record is created when you call System.schedule or schedule a class in Setup. It exists for as long as the job stays on the schedule. Each time the job fires, the platform calls execute and passes a context whose getTriggerId() returns that same record's ID. So the value is stable across runs. A job that fires every night gets the same ID every night.
Reading job details from inside the run
The most common use of the context is to look up the CronTrigger that started the run. The query below reads the fields that are useful for logging.
public class LoggedJob implements Schedulable {
public void execute(SchedulableContext sc) {
CronTrigger ct = [
SELECT Id, CronJobDetail.Name, CronExpression,
TimesTriggered, PreviousFireTime, NextFireTime
FROM CronTrigger
WHERE Id = :sc.getTriggerId()
];
System.debug(
'Running ' + ct.CronJobDetail.Name
+ ', expression ' + ct.CronExpression
+ ', run number ' + (ct.TimesTriggered + 1)
+ ', next run ' + ct.NextFireTime
);
}
}Some details to be aware of:
CronJobDetail.Nameis the name you passed toSystem.schedule. It is the easiest way to tell which of several schedules of the same class is running.- The query uses one SOQL statement. It counts against the same governor limits as the rest of
execute, so do not run it in a loop. TimesTriggeredcounts runs that have already fired. Whether it already includes the current run depends on timing, so treat it as approximate in log messages and do not use it for logic.NextFireTimeisnullwhen the job has no future runs, for example a job scheduled with a specific year that has now passed.
Three IDs that are easy to confuse
A scheduled job that starts other asynchronous work touches several kinds of IDs. Mixing them up produces confusing query results, because a query against the wrong object simply returns no rows.
| ID | Where it comes from | Object to query | Key prefix |
|---|---|---|---|
| Scheduler ID | `System.schedule` return value, `sc.getTriggerId()` | `CronTrigger` | `08e` |
| Job definition ID | `CronTrigger.CronJobDetailId` | `CronJobDetail` | `08a` |
| Async job ID | `Database.executeBatch`, `System.enqueueJob` return values | `AsyncApexJob` | `707` |
sc.getTriggerId() is never an AsyncApexJob ID. If your scheduled class starts a batch, the batch gets its own 707 ID, and you need to keep both if you want to relate them in a log.
Passing the trigger ID to the work you start
A scheduled class often does nothing but start a batch or queueable job. If the downstream code needs to know which schedule started it, pass the ID in through the constructor. This keeps the batch class free of any dependency on SchedulableContext, which also keeps it easy to test.
public class ArchiveTasksBatch implements Database.Batchable<SObject> {
private final Id schedulerId;
public ArchiveTasksBatch(Id schedulerId) {
this.schedulerId = schedulerId;
}
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) {
System.debug('Batch ' + bc.getJobId() + ' started by scheduler ' + schedulerId);
}
}
public class NightlyArchive implements Schedulable {
public void execute(SchedulableContext sc) {
Id batchJobId = Database.executeBatch(new ArchiveTasksBatch(sc.getTriggerId()), 200);
System.debug('Scheduler ' + sc.getTriggerId() + ' started batch ' + batchJobId);
}
}The two debug lines show the relationship from both sides. In execute, you know the scheduler ID and the new batch ID. In finish, you know the batch ID from bc.getJobId() and the scheduler ID from the constructor argument. If you write both to a log record, you can later trace a failed batch back to the schedule that created it.
Aborting the job from inside itself
Because the context gives you the CronTrigger ID, a job can remove itself from the schedule. This is the standard way to build a one-time job that runs once and then cleans up.
public class OneTimeMigration implements Schedulable {
public void execute(SchedulableContext sc) {
// Do the work first so a failure leaves the job in place for diagnosis.
Database.executeBatch(new ArchiveTasksBatch(sc.getTriggerId()), 200);
System.abortJob(sc.getTriggerId());
}
}Think about the order of operations. If execute throws an unhandled exception before it reaches System.abortJob, the job stays scheduled and will fire again at the next time in its cron expression. If you abort first and the work then fails, the work is lost and nothing will retry it. Which behavior you want depends on the task. For a migration that must happen exactly once, you might abort first and rely on logging to report a failure. For work that is safe to repeat, abort last.
Rescheduling from inside the job
A cron expression cannot express "every 5 minutes" in a single entry, and a single entry cannot express an interval that changes between runs. A job can use the context to replace itself with a new entry instead. This is the standard way to get a custom or adaptive interval.
public class SelfReschedulingJob implements Schedulable {
public void execute(SchedulableContext sc) {
// 1. Do the work, or start a batch or queueable job.
// 2. Remove the entry that just fired.
System.abortJob(sc.getTriggerId());
// 3. Schedule the next run about 15 minutes from now.
Datetime next = System.now().addMinutes(15);
String cron = next.format('s m H d M \'?\' yyyy');
System.schedule('Self rescheduling ' + next.getTime(), cron, new SelfReschedulingJob());
}
}Three points make this pattern work:
- Unique names. Job names are not allowed to repeat among scheduled jobs. The example adds the next run time in milliseconds to the name so each new entry is distinct.
- The cron string is built for one moment. The format
s m H d M ? yyyyproduces a one-time expression for an exact second, minute, hour, day, month and year. The?stands for "no specific day of week". - The chain is fragile. If the work in step 1 throws before step 3, the chain stops and nothing is left on the schedule. Wrap step 1 in
try/catch, or reschedule first and then do the work.
Testing code that uses the context
There are two ways to get a SchedulableContext into a test.
Run the job through the scheduler. This is the recommended approach, because the context is real and getTriggerId() returns a real CronTrigger ID. Jobs scheduled between Test.startTest() and Test.stopTest() run synchronously when Test.stopTest() is called.
public class StampingJob implements Schedulable {
public void execute(SchedulableContext sc) {
Id triggerId = sc.getTriggerId();
insert new Task(
Subject = 'Scheduled run ' + triggerId,
Status = 'Completed',
Priority = 'Normal'
);
}
}@IsTest
private class StampingJobTest {
@IsTest
static void contextCarriesTheTriggerId() {
Test.startTest();
Id jobId = System.schedule(
'Test stamping job', '0 0 0 15 3 ? 2099', new StampingJob()
);
Test.stopTest();
List<Task> stamps = [
SELECT Id FROM Task WHERE Subject = :('Scheduled run ' + jobId)
];
System.assertEquals(1, stamps.size(), 'Job should run once and see its own trigger ID');
}
}The test proves that the ID the job saw during its run is the same ID that System.schedule returned. Nothing else in the test depends on the clock, because the job fires at Test.stopTest() regardless of the year in the cron expression.
Call execute directly with a stub. SchedulableContext is an interface, so a test can implement it. This is useful when the logic in execute is large and you want to test it without the scheduler.
@IsTest
private class StubContextTest {
private class StubContext implements SchedulableContext {
public Id getTriggerId() {
return null;
}
}
@IsTest
static void executeRunsWithAStubContext() {
Test.startTest();
new OneTimeMigration().execute(new StubContext());
Test.stopTest();
}
}This stub has a limit. A made-up ID matches no CronTrigger, so a job that queries by sc.getTriggerId() throws a QueryException for "no rows for assignment", and System.abortJob with a made-up ID fails as well. Passing null as the context has the same problem if your code dereferences it. If a class needs the context for these calls, test it through System.schedule. If you want direct-call tests for the business logic, move that logic to a separate method that takes plain arguments, and keep execute as a thin wrapper that reads the context and passes values along.
Common mistakes
- Querying with the wrong ID. Using the ID returned by
Database.executeBatchin aCronTriggerquery returns no rows. Match the ID to its object using the table above. - Assuming the name is available without a query. The context gives you only an ID. Any other detail, including the job name, needs a SOQL query against
CronTrigger. - Storing the trigger ID across a reschedule. After
System.abortJoband a newSystem.schedule, the entry has a new ID. Old IDs saved in custom settings or log records no longer point to a live job. - Heavy work after reading the context. The
executemethod has the limits of a synchronous Apex transaction. Read the ID, then hand heavy work to a batch or queueable job. - Relying on
TimesTriggeredfor control flow. Use it for logging. Keep any counter that drives behavior in your own data.
Summary
SchedulableContext gives your job one piece of information, the CronTrigger ID, and that ID is the key to everything else you need at run time. You can use it to read the job's name and timing, to link a scheduler to the batch it started, to abort the job from the inside, and to replace the job with a new entry. Test these paths through System.schedule and Test.stopTest() so the context is real, and keep business logic out of execute so that direct tests do not need a context at all.
Exercise
A scheduled class runs nightly and starts a batch with Database.executeBatch. In the batch's finish method, a developer runs [SELECT Id FROM CronTrigger WHERE Id = :bc.getJobId()] to find the schedule that started it, and always gets zero rows. What is wrong, and how would you fix it?
Show answer
bc.getJobId() returns the AsyncApexJob ID of the batch (prefix 707), not a CronTrigger ID (prefix 08e), so the CronTrigger query can never match. Fix it by passing sc.getTriggerId() from the scheduled class into the batch constructor, storing it in a field, and using that field in the CronTrigger query inside finish.
Exercise
A one-time Schedulable class calls System.abortJob(sc.getTriggerId()) as the first line of execute, then starts a batch. The batch fails to start because of an unhandled exception. Will the job run again, and what would you change if the work must be retried?
Show answer
No. The job already removed its own schedule entry before the failure, so nothing is left to fire again. To allow a retry, move System.abortJob to the end of execute, after the work has been started successfully, or catch the exception and schedule a new entry.