Sub topic 8
Monitoring and aborting jobs
This chapter assumes you can write and schedule a Schedulable class with System.schedule, and that you are comfortable running SOQL in the Developer Console. Once a job is scheduled, it runs without anyone watching. You need to be able to answer three questions about it:
- Is it still on the schedule?
- When does it run next?
- Did the last run work?
You also need a way to remove the job when it is no longer wanted.
Two records, two questions
Salesforce keeps two kinds of records for scheduled Apex, and they answer different questions.
| Record | Describes | Answers |
|---|---|---|
| `CronTrigger` | The schedule entry | Is it scheduled? When does it fire next? How many times has it fired? |
| `AsyncApexJob` | One execution of async Apex | Did this run finish? Did it fail? What was the error? |
System.schedule returns the ID of the CronTrigger. That ID stays the same for the life of the schedule entry. Every time the job fires, Salesforce creates a new AsyncApexJob row with its own ID.
Beginners often query CronTrigger to check whether the last run succeeded. It cannot tell you that. CronTrigger only describes the timetable, and AsyncApexJob describes what happened.
Querying CronTrigger
CronTrigger has a relationship to CronJobDetail, which holds the job name and type. The fields you will use most are:
CronJobDetail.Name: the name you passed toSystem.schedule.CronJobDetail.JobType: the kind of job. Scheduled Apex has the value'7'. Other job types, such as reporting snapshots, share the object.CronExpression: the cron string the job was scheduled with.State: where the job is in its lifecycle (see below).StartTime,EndTime: the window in which the job is allowed to fire.PreviousFireTime,NextFireTime: the last and next run times.PreviousFireTimeis null until the first run.TimesTriggered: the number of times the job has fired.OwnerId: the user the job runs as.
This query lists every scheduled Apex job in the org, soonest first:
List<CronTrigger> jobs = [
SELECT Id, CronJobDetail.Name, CronExpression, State,
PreviousFireTime, NextFireTime, TimesTriggered
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
ORDER BY NextFireTime ASC NULLS LAST
];
for (CronTrigger ct : jobs) {
System.debug(
ct.CronJobDetail.Name + ' | ' + ct.State +
' | next: ' + ct.NextFireTime +
' | fired ' + ct.TimesTriggered + ' times'
);
}Run this as anonymous Apex and open the debug log to read the output. The JobType = '7' filter keeps non-Apex entries out of the result.
Job states
The State field tells you what the scheduler is doing with the entry right now.
| State | Meaning |
|---|---|
| `WAITING` | Scheduled, with a future fire time. This is the normal resting state. |
| `ACQUIRED` | The scheduler has picked the job up and is about to run it. |
| `EXECUTING` | The `execute` method is running. |
| `COMPLETE` | The job has run its last scheduled time. |
| `ERROR` | The scheduler hit an error with the entry itself. |
| `DELETED` | The entry has been removed. |
| `PAUSED`, `BLOCKED`, `PAUSED_BLOCKED` | The job is held back. These are rare in everyday work. |
The diagram shows the usual path through these states.
A job with a repeating cron expression returns to WAITING after every run. A job scheduled for a single date, such as 0 0 0 15 3 ? 2099, has no further fire times after its run. Once it finishes, it no longer appears among your scheduled jobs. Do not write code that expects to find a finished one-off job by name.
What an exception does
If execute throws an unhandled exception, that run fails. The schedule entry stays in place, and the next fire time still arrives. A single bad night does not cancel the job. The failure is recorded on the AsyncApexJob row for that run, and Salesforce sends an email about the unhandled exception to the job's owner.
This is useful, but it also hides problems. A job can fail every night for a month while its CronTrigger shows WAITING with a healthy NextFireTime. Monitoring has to include AsyncApexJob.
Checking what happened with AsyncApexJob
Each execution of a scheduled class appears in AsyncApexJob with JobType = 'ScheduledApex'. These are the same rows you see on the Apex Jobs page in Setup.
List<AsyncApexJob> runs = [
SELECT Id, ApexClass.Name, Status, NumberOfErrors,
ExtendedStatus, CompletedDate
FROM AsyncApexJob
WHERE JobType = 'ScheduledApex'
AND CreatedDate = LAST_N_DAYS:7
ORDER BY CreatedDate DESC
LIMIT 50
];
for (AsyncApexJob run : runs) {
System.debug(
run.ApexClass.Name + ' | ' + run.Status +
' | errors: ' + run.NumberOfErrors +
' | ' + run.ExtendedStatus
);
}Status is one of Queued, Processing, Completed, Failed or Aborted, among others. When a run fails, ExtendedStatus usually holds the error message.
If your scheduled class starts a batch job, as in the previous chapter, there are two levels of records. The scheduled run shows as ScheduledApex. The batch it starts gets its own AsyncApexJob row with JobType = 'BatchApex', and that row carries the batch's TotalJobItems, JobItemsProcessed and NumberOfErrors. A scheduled run can show Completed while the batch it launched fails. Check both.
Monitoring in Setup
You do not need code for a quick look. Setup has two pages that mirror the queries above:
- Scheduled Jobs lists
CronTriggerentries. It shows the job name, the submitter, the previous and next run times, and a Del link that aborts the job. - Apex Jobs lists
AsyncApexJobrows for all async Apex types. Filter by job type to focus on scheduled and batch runs.
Use Setup for one-off checks. Use SOQL when you want to assert on the results, build a report, or alert someone.
Aborting a job
System.abortJob takes the ID of a CronTrigger and removes it from the schedule. The ID is the value System.schedule returned when you created the job.
Id jobId = System.schedule(
'Escalate stale cases',
'0 0 13 * * ?',
new EscalateStaleCases()
);
// Later, remove it:
System.abortJob(jobId);Most of the time you will not have the ID to hand, so you look the job up by name first. This helper does that and reports how many entries it removed:
public class ScheduledJobAdmin {
public static Integer abortByName(String jobName) {
List<CronTrigger> matches = [
SELECT Id
FROM CronTrigger
WHERE CronJobDetail.Name = :jobName
];
for (CronTrigger ct : matches) {
System.abortJob(ct.Id);
}
return matches.size();
}
}Call it from anonymous Apex with ScheduledJobAdmin.abortByName('Escalate stale cases');.
Aborting a job has some effects you should know about:
- It stops future runs. An execution already in progress is not guaranteed to stop.
- An aborted job cannot be resumed. To get it back, call
System.scheduleagain. - A job name must be unique among your scheduled jobs. If you abort a job and immediately re-create it with the same name, make sure the abort has gone through first.
Aborting from inside the job
The SchedulableContext passed to execute knows its own CronTrigger ID. A job can use it to switch itself off, for example after a fixed number of runs or when a feature flag turns off:
public class LimitedRunJob implements Schedulable {
public void execute(SchedulableContext sc) {
CronTrigger ct = [
SELECT TimesTriggered
FROM CronTrigger
WHERE Id = :sc.getTriggerId()
];
// ... do the work ...
if (ct.TimesTriggered >= 9) {
System.abortJob(sc.getTriggerId());
}
}
}The count is read during the run, so TimesTriggered may not yet include the current execution. Test the boundary rather than assuming it.
Scheduling safely: avoid duplicates
Calling System.schedule twice with the same name fails with an error saying that a job with that name is already scheduled. This often surprises people when a setup script, a post-install step or a button runs twice.
The usual fix is to check before scheduling:
public class ScheduledJobAdmin {
public static Id ensureScheduled(String jobName, String cronExp, Schedulable job) {
List<CronTrigger> existing = [
SELECT Id
FROM CronTrigger
WHERE CronJobDetail.Name = :jobName
LIMIT 1
];
if (!existing.isEmpty()) {
return existing[0].Id;
}
return System.schedule(jobName, cronExp, job);
}
}The helper is idempotent: running it ten times leaves one entry. If you put both methods in one class, as shown here and above, merge them into a single ScheduledJobAdmin class.
A changed cron expression needs different handling. This helper returns the old entry without checking its schedule. To change a schedule, compare CronExpression on the existing record with the new one. If they differ, abort the old job and schedule the new one.
Watching the 100-job ceiling
An org can hold at most 100 scheduled Apex jobs at a time. When you reach the limit, System.schedule throws an exception. Jobs that nobody remembers can quietly use up that allowance. Count the entries now and then:
Integer used = [
SELECT COUNT()
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
];
System.debug('Scheduled Apex jobs in use: ' + used + ' of 100');The same listing shows jobs that belong to users who have left the company. Abort those on purpose rather than by accident.
Aborting before a deployment
Salesforce protects classes that have pending or running scheduled jobs. If you try to modify or deploy a class while a job that uses it is scheduled, the change can be refused. Production orgs have a setting that allows deployments while Apex jobs are pending or in progress. Without that setting, the usual process is:
- Query the jobs that use the class.
- Record their names and cron expressions.
- Abort them.
- Deploy.
- Schedule them again with the saved names and expressions.
Keep the cron expressions in code, for example as constants on the class or in custom metadata. That way step 5 does not depend on someone's memory or on a screenshot of Setup.
Testing abort logic
In a test, scheduling and aborting both work normally. Assert on the state after the abort:
@IsTest
private class ScheduledJobAdminTest {
@IsTest
static void abortRemovesTheJob() {
Test.startTest();
Id jobId = System.schedule(
'Test abort job',
'0 0 0 15 3 ? 2099',
new EscalateStaleCases()
);
Integer aborted = ScheduledJobAdmin.abortByName('Test abort job');
Test.stopTest();
System.assertEquals(1, aborted);
Integer remaining = [
SELECT COUNT()
FROM CronTrigger
WHERE Id = :jobId AND State != 'DELETED'
];
System.assertEquals(0, remaining);
}
}The query excludes DELETED so the test passes whether or not the removed entry is still visible.
Practical checklist
- Query
CronTriggerto see whether a job is scheduled and when it runs next. - Query
AsyncApexJobto see whether runs succeeded. - If the scheduled class starts a batch, check the batch's own
AsyncApexJobrow too. - Name every job, and look it up by that name rather than by a stored ID.
- Make scheduling idempotent so repeated setup does not fail.
- Count jobs against the 100 limit.
- Keep cron expressions in code so you can reschedule after an abort.
Exercise
A scheduled job shows State = WAITING and a NextFireTime tomorrow, but the data it should update has not changed for a week. Which object do you query next, and which fields would you look at?
Show answer
Query AsyncApexJob with JobType = 'ScheduledApex' for the job's class. Look at Status, NumberOfErrors and ExtendedStatus for each recent run. CronTrigger only describes the timetable, so a WAITING state is normal even when every run fails. If the class starts a batch, also query the AsyncApexJob rows with JobType = 'BatchApex' for errors.
Exercise
Write a short Apex snippet that aborts every scheduled Apex job whose name starts with 'Temp '.
Show answer
List<CronTrigger> temps = [SELECT Id FROM CronTrigger WHERE CronJobDetail.JobType = '7' AND CronJobDetail.Name LIKE 'Temp %']; for (CronTrigger ct : temps) { System.abortJob(ct.Id); } The JobType filter limits the query to scheduled Apex, and LIKE 'Temp %' matches the name prefix.
Exercise
Why is it a mistake to call System.schedule from a setup script without checking for an existing job, and how do you fix it?
Show answer
A second call with the same job name fails because the name is already scheduled. Query CronTrigger by CronJobDetail.Name first and return the existing ID if a record is found. Schedule only when none exists. This makes the script safe to run repeatedly.