Sub topic 8
Monitoring and aborting jobs
This chapter assumes you can write a Schedulable class, build a cron expression, and call System.schedule. It also assumes you know basic SOQL. Here you will learn how to find a scheduled job, read its state, and remove it.
What CronTrigger records tell you
Every job created with System.schedule or from Setup is stored as a CronTrigger record. The record holds the schedule and the job's current status. A related CronJobDetail record holds the job name and type.
These are the fields you will use most:
| Field | Meaning |
|---|---|
| `Id` | The job ID. `System.schedule` returns this value. |
| `CronJobDetail.Name` | The name you gave the job. |
| `CronExpression` | The cron expression the job uses. |
| `State` | The job's current state, such as `WAITING`. |
| `NextFireTime` | When the job will run next. It is null once the job has no further runs. |
| `PreviousFireTime` | When the job last ran. It is null if the job has never run. |
| `TimesTriggered` | How many times the job has run. |
Querying a job
You can query by name, by ID, or by state. This example looks up one job and prints its status.
CronTrigger ct = [
SELECT Id, CronJobDetail.Name, State, NextFireTime, TimesTriggered
FROM CronTrigger
WHERE CronJobDetail.Name = 'Escalate stale cases'
];
System.debug(ct.State + ' next run: ' + ct.NextFireTime);The query returns exactly one row only if a job with that name exists. If no job matches, assigning the result to a single CronTrigger throws a QueryException. Query into a list when you are not sure the job exists.
Job states
A job moves through a small set of states. A scheduled job waits for its next fire time, runs, and then either waits again or finishes.
In practice, WAITING is the state you see most often. A job in EXECUTING is running at this moment. A job that has finished all its runs, such as one with a fixed year in the cron expression, is COMPLETE for a short time and is later removed from the schedule.
Aborting a job
Use System.abortJob with the job ID. It deletes the CronTrigger record, so the job never runs again.
CronTrigger ct = [
SELECT Id
FROM CronTrigger
WHERE CronJobDetail.Name = 'Escalate stale cases'
];
System.abortJob(ct.Id);You can also remove a job in Setup. Open Scheduled Jobs, find the job, and click Del. Both methods have the same effect.
Aborting a job does not stop a batch job that the scheduled class already started. A batch job has its own ID and its own record in AsyncApexJob. To stop it, call System.abortJob with the batch job's ID.
Rescheduling safely
You cannot edit a scheduled job in place. To change its timetable, abort it and schedule it again. Scheduling the same class twice with different names creates two jobs, and both will run. This is a common cause of duplicate work after a deployment.
A simple guard avoids duplicates. It aborts any existing job with the same name before it schedules a new one.
public class EscalateStaleCasesScheduler {
public static Id reschedule(String jobName, String cronExp) {
for (CronTrigger old : [
SELECT Id
FROM CronTrigger
WHERE CronJobDetail.Name = :jobName
]) {
System.abortJob(old.Id);
}
return System.schedule(jobName, cronExp, new EscalateStaleCases());
}
}Finding what ran
CronTrigger tells you about the schedule. It does not record the result of each run. For that, check these places:
- Apex Jobs in Setup lists each run of a scheduled class. Each run appears as an
AsyncApexJobrecord with aJobTypeofScheduledApex. A failed run shows its status and error message. - Debug logs show what happened inside a run, if a trace flag is active for the user who owns the job.
- Batch runs appear as separate
AsyncApexJobrows with aJobTypeofBatchApex.
This query lists recent scheduled runs and any that failed.
List<AsyncApexJob> runs = [
SELECT Id, Status, ExtendedStatus, CompletedDate
FROM AsyncApexJob
WHERE JobType = 'ScheduledApex'
ORDER BY CreatedDate DESC
LIMIT 20
];
for (AsyncApexJob run : runs) {
System.debug(run.Status + ' ' + run.ExtendedStatus);
}Common errors
QueryException: List has no rows. The job name did not match. Names are compared exactly, so check spelling and case.- Duplicate runs. The class was scheduled more than once under different names. Query by
CronJobDetail.Nameor list all jobs and abort the extras. - Job never fires. Check
StateandNextFireTime. A nullNextFireTimemeans no more runs are planned. - Cannot abort from a test. Test jobs are removed when the test finishes, so you do not need to abort them.
Exercise
A teammate says a nightly job did not run last night. Which two objects would you query first, and what would you look for in each?
Show answer
Query CronTrigger by CronJobDetail.Name to confirm the job still exists, that State is WAITING, and that PreviousFireTime and NextFireTime are what you expect. Then query AsyncApexJob with JobType = 'ScheduledApex' to see whether a run happened and whether its Status is Failed, with the error in ExtendedStatus.
Exercise
You change the cron expression in your code and deploy. Why does the job keep running on the old timetable, and how do you fix it?
Show answer
A scheduled job stores its cron expression when it is created, so a code change does not update it. Abort the existing job with System.abortJob and call System.schedule again with the new expression.