Sub topic 3
Monitoring and Aborting Scheduled Apex Jobs
Assume you know basic Apex, SOQL, DML, and governor limits. A scheduled job is represented by a CronTrigger record. Query it to inspect the job, then call System.abortJob to cancel it.
Monitoring and aborting jobs
CronTrigger contains the schedule state, next run time, and number of executions. The related CronJobDetail record contains the job name.
CronTrigger job = [
SELECT Id, CronJobDetail.Name, State, NextFireTime, TimesTriggered
FROM CronTrigger
WHERE CronJobDetail.Name = 'Escalate stale cases'
LIMIT 1
];
System.debug(
job.CronJobDetail.Name + ' is ' + job.State +
'; next run: ' + job.NextFireTime
);
System.abortJob(job.Id);Use the job ID returned by System.schedule when possible. Names are not always unique, especially in shared administration code.
Testing scheduled jobs
Put scheduling inside Test.startTest() and Test.stopTest(). Salesforce runs asynchronous work during Test.stopTest(). To test scheduling metadata without relying on a future date, query the trigger before stopTest.
@IsTest
private class EscalateStaleCasesTest {
@IsTest
static void schedulesJob() {
String cron = '0 0 0 15 3 ? 2099';
Test.startTest();
Id jobId = System.schedule(
'Test escalate stale cases',
cron,
new EscalateStaleCases()
);
CronTrigger scheduled = [
SELECT CronExpression, TimesTriggered
FROM CronTrigger
WHERE Id = :jobId
];
System.assertEquals(cron, scheduled.CronExpression);
System.assertEquals(0, scheduled.TimesTriggered);
Test.stopTest();
}
}Add separate tests for the class’s business behavior, including records that should and should not change.
Limits and restrictions to plan around
Scheduled Apex still follows governor limits when its execute method runs. It also consumes an org-wide scheduled-job limit, so avoid creating duplicate recurring jobs. A schedule controls when work starts, not the exact completion time. Jobs can be delayed by platform load.
For large data sets, schedule a small coordinator that starts Batch Apex. Do not query and update every record directly in the scheduled transaction.
Designing reliable scheduled jobs
Make each run safe to repeat. Filter records by current state, use one bulk query and one bulk DML operation, and log failures where operators can find them. Give jobs clear names and retain their IDs for administration. Abort obsolete schedules during deployment or configuration changes.
Exercise
Which object shows a scheduled job’s next run time, and which method cancels it?
Show answer
Query CronTrigger for NextFireTime, then call System.abortJob with the trigger ID.