Sub topic 6
Using SchedulableContext to identify the running job
This chapter assumes you can write a Schedulable class and call System.schedule, and that you can query CronTrigger records with SOQL. Every execute method of a scheduled class receives a SchedulableContext argument, and this chapter shows what it gives you.
What the context contains
SchedulableContext is an interface with one method, getTriggerId(). It returns the ID of the CronTrigger record that represents the schedule firing the current run.
That ID is the same value System.schedule returned when the job was created. If you scheduled the job from Setup, it is the ID of the CronTrigger that Setup created.
sequenceDiagramReplace the above with the diagram below.
Reading job details from inside the job
The ID is a key into CronTrigger. Query it when a run needs to know its own name, its previous run time, or the next one.
public class EscalateStaleCasesLogged implements Schedulable {
public void execute(SchedulableContext sc) {
CronTrigger ct = [
SELECT CronJobDetail.Name, CronExpression, PreviousFireTime, NextFireTime
FROM CronTrigger
WHERE Id = :sc.getTriggerId()
];
System.debug('Running ' + ct.CronJobDetail.Name
+ ', last run ' + ct.PreviousFireTime
+ ', next run ' + ct.NextFireTime);
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
LIMIT 200
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
}
}The query counts against the governor limits of the scheduled transaction, like any other SOQL. Run it only if you use the result.
Aborting the job from itself
Because the context gives you the ID, a job can remove its own schedule. This suits work that should repeat until a condition is met.
public class EscalateUntilDone implements Schedulable {
public void execute(SchedulableContext sc) {
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
LIMIT 200
];
if (stale.isEmpty()) {
System.abortJob(sc.getTriggerId());
return;
}
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
}
}When no stale cases remain, the job aborts its own CronTrigger and stops firing. The return ends the current run cleanly.
Passing the ID onward
When the scheduled class starts a batch job, you can hand the trigger ID to the batch. The batch can then record which schedule started it. Store it in a field of the batch class, set through the constructor.
public class ArchiveTasksBatch implements Database.Batchable<SObject> {
private final Id scheduleId;
public ArchiveTasksBatch(Id scheduleId) {
this.scheduleId = scheduleId;
}
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 schedule ' + scheduleId);
}
}
public class NightlyTaskCleanupTracked implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new ArchiveTasksBatch(sc.getTriggerId()), 200);
}
}Common errors
- Mixing up two IDs.
sc.getTriggerId()is aCronTriggerID.Database.executeBatchreturns anAsyncApexJobID, andBatchableContext.getJobId()returns that same type. QueryingAsyncApexJobwith a trigger ID returns no rows. - Passing
nullin tests. Callingnew MyJob().execute(null)in a test works only ifexecutenever touchessc. Callingsc.getTriggerId()onnullthrows aNullPointerException. Schedule the job withSystem.scheduleinsideTest.startTest()andTest.stopTest()instead, so the platform supplies a real context. The job runs whenTest.stopTest()is called. - Querying after a self-abort. Once
System.abortJobruns, the schedule is gone. A later query on that ID in the same run may return no row, so read what you need first. - Assuming the ID is stable across reschedules. Aborting and scheduling again creates a new
CronTriggerwith a new ID. Look jobs up byCronJobDetail.Namewhen you need to find them again.
Exercise
A scheduled class starts a batch with Database.executeBatch. In the batch's finish method, you query CronTrigger using bc.getJobId() and get no rows. Why, and which ID should you use instead?
Show answer
bc.getJobId() returns the AsyncApexJob ID of the batch run, not a CronTrigger ID. To reach the CronTrigger, pass sc.getTriggerId() from the scheduled class into the batch, for example through its constructor, and query CronTrigger with that stored value.