Sub topic 10
Limits and restrictions to plan around
Scheduled Apex looks simple: one interface, one method, one cron string. Most production problems come from limits and restrictions you can't see in that code. This chapter lists them, explains how each one fails, and shows how to design around it.
This chapter assumes you can write a Schedulable class, read a cron expression, call System.schedule, and query CronTrigger. It also assumes you know what governor limits are. Earlier chapters cover those topics.
Limits that apply to the whole org
Three limits apply to every scheduled job in the org, not to a single class.
| Limit | Value | What happens when you hit it |
|---|---|---|
| Scheduled Apex jobs at one time | 100 | `System.schedule` throws a `LimitException` |
| Asynchronous Apex executions per 24 hours | 250,000, or licenses × 200 if that is greater | Jobs are not run until the 24-hour window frees capacity |
| Active or queued Batch Apex jobs | 5 | Extra batch jobs go to the Apex Flex Queue in `Holding` status |
Check the current values in the Apex Developer Guide before you rely on them. Salesforce has changed these numbers between releases.
The 100-job ceiling
The 100-job limit counts scheduled Apex jobs, whatever class they run. A job that has finished all its fire times is removed from the count. A recurring job counts until you abort it.
The limit is easy to reach when code creates jobs dynamically. A trigger that calls System.schedule for every inserted record can use up the whole allowance in one bulk load. Schedule a small, fixed set of jobs, and let each job loop over the records it needs to handle.
If you do create jobs in code, check the count first and fail with a clear message:
public class JobScheduler {
public class JobLimitException extends Exception {}
// Job type '7' is Scheduled Apex in CronJobDetail.JobType.
private static final Integer MAX_SCHEDULED_JOBS = 100;
public static Id scheduleOnce(String jobName, String cronExp, Schedulable job) {
Integer existing = [
SELECT COUNT()
FROM CronTrigger
WHERE CronJobDetail.Name = :jobName
];
if (existing > 0) {
throw new JobLimitException('A job named "' + jobName + '" already exists.');
}
Integer total = [
SELECT COUNT()
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
];
if (total >= MAX_SCHEDULED_JOBS) {
throw new JobLimitException('The org already has ' + total + ' scheduled Apex jobs.');
}
return System.schedule(jobName, cronExp, job);
}
}The name check matters because each scheduled job needs a unique name. Scheduling a second job with a name that is already in use throws an AsyncException.
The daily execution allowance
The daily limit is shared with every other kind of asynchronous Apex: Batch Apex, Queueable Apex and future methods. A job that runs every five minutes uses 288 executions a day, but that is a small share. The real cost is what the job starts. A scheduled job that launches a batch of 2,000 batches each night uses one scheduled execution plus one execution per batch chunk. Count the whole chain when you estimate your daily usage.
Limits inside a single execution
When the scheduler calls execute, your code runs as an asynchronous transaction. It gets the asynchronous governor limits, not the synchronous ones.
| Limit | Synchronous | Asynchronous (scheduled) |
|---|---|---|
| SOQL queries | 100 | 200 |
| DML statements | 150 | 150 |
| Records retrieved by SOQL | 50,000 | 50,000 |
| Heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
| Callouts | 100 | 100 |
The higher ceilings don't change the design rule. The query in the first example uses LIMIT 200 so the job can't process more records than it can handle in one run. If the work could grow beyond that, hand it to Batch Apex instead of relying on the larger limits.
Silent truncation is the common bug
A scheduled job with LIMIT 200 that never finds a way to process record 201 will leave work undone without any error. Log how many records you processed, and compare it with the number you expected.
public class EscalateStaleCases 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
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
if (stale.size() == 200) {
System.debug(LoggingLevel.WARN,
'EscalateStaleCases hit its 200 record cap. More cases may be waiting.');
}
}
}Because the job runs every day, the backlog drains over several runs. That is acceptable for some tasks and wrong for others. Decide on purpose.
Restrictions on what execute can do
No synchronous callouts
A scheduled execute method can't make a synchronous callout to an external service. The platform rejects it at run time with a callout exception. Two patterns work around this:
- Move the callout into a method annotated
@future(callout=true)and call that method fromexecute. - Start a Batch Apex job whose class also implements
Database.AllowsCallouts.
The first pattern fits a single request:
public class RateSyncService {
@future(callout=true)
public static void fetchRates() {
HttpRequest req = new HttpRequest();
// Rates_API is a Named Credential you create in Setup.
req.setEndpoint('callout:Rates_API/v1/latest');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
System.debug(LoggingLevel.ERROR, 'Rate sync failed: ' + res.getStatus());
}
}
}
public class RateSyncSchedule implements Schedulable {
public void execute(SchedulableContext sc) {
RateSyncService.fetchRates();
}
}Use the batch pattern when you need to make many calls, because each batch chunk gets its own callout limit.
Job state is serialized when you schedule
When you call System.schedule, Salesforce serializes the Schedulable instance and stores it. Every later run uses that stored copy. Three consequences follow.
- Constructor arguments and member variables are frozen at scheduling time. If you pass a list of record IDs to the constructor, the job uses those IDs forever, even after the records change. Pass criteria, not data, and query inside
execute. - Member variables that can't be serialized cause an error when you schedule. Mark them
transientand rebuild them insideexecute. - Static variables do not survive between runs. Each execution starts with fresh statics.
public class DigestJob implements Schedulable {
private final String region; // serialized, fixed at scheduling time
private transient Map<Id, Account> accountCache; // not stored, rebuilt on each run
public DigestJob(String region) {
this.region = region;
}
public void execute(SchedulableContext sc) {
accountCache = new Map<Id, Account>([
SELECT Id, Name FROM Account WHERE BillingState = :region LIMIT 1000
]);
System.debug('Loaded ' + accountCache.size() + ' accounts for ' + region);
}
}Running as a user, in system mode
The code runs in system mode. Object and field permissions are not enforced unless you enforce them yourself, for example with WITH USER_MODE in SOQL. Sharing follows the class declaration (with sharing or without sharing).
The job is still tied to the user who scheduled it. The cron expression is interpreted in that user's time zone. If your team changes user time zones, or someone schedules the job from an account with a different time zone, the job runs at a different clock time than you expect. Schedule production jobs from a dedicated integration user, and set that user's time zone deliberately.
Deployment restrictions
A class with pending scheduled jobs is locked against casual edits. If a Schedulable class has active jobs, you can't change it, or the classes it references, through the Setup UI or the Developer Console. A deployment fails with an error that says the class has jobs pending or in progress.
You have three ways to handle this:
- Abort the job, deploy, and schedule it again. This works but leaves a gap in the schedule.
- In Setup, open Deployment Settings and enable the option that allows deployments while Apex jobs are pending or in progress. Do this in the target org only, and read the warning on the page first.
- Make the scheduled class a thin wrapper that never changes. Put the logic in other classes. Those classes are still referenced by the scheduled class, so the lock applies to them too, so the deployment setting is usually the practical solution.
Whichever you choose, put the redeploy-and-reschedule steps in your release checklist.
Timing is not exact
The scheduler queues your job at the cron time. It doesn't guarantee that the job starts at that second. When the org's async queue is busy, the job can start minutes late. Don't write logic that assumes System.now() inside execute equals the scheduled time.
If a run fails with an unhandled exception, that run fails and the schedule stays in place. The next fire time still happens. Nothing retries the failed run, so a missed window is simply missed. Design each run to pick up whatever is outstanding, not only the work from the previous interval.
This is why the example job selects all open cases older than seven days, not cases from the last 24 hours. A skipped run costs one day of delay, not a permanent gap.
Choosing where the work should run
The diagram summarizes the decision. Start with the size of the data and whether the job makes callouts.
Batch jobs started from a schedule
At most five batch jobs can be queued or active at once. When you call Database.executeBatch while five are already running, the new job doesn't fail. It goes to the Apex Flex Queue with Holding status, and the platform moves it up when a slot opens. The Flex Queue holds up to 100 jobs.
Two scheduled jobs that start batches at the same time, such as two midnight jobs, can delay each other. Stagger start times by a few minutes, and keep the batch count in mind when you add a new scheduled job.
Monitoring against the limits
You can see how close the org is to the ceilings with a query and a glance at Setup.
Integer scheduled = [
SELECT COUNT()
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
];
System.debug('Scheduled Apex jobs: ' + scheduled + ' of 100');
List<AsyncApexJob> active = [
SELECT Id, ApexClass.Name, Status
FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND Status IN ('Queued', 'Processing', 'Preparing', 'Holding')
];
System.debug('Batch jobs active or waiting: ' + active.size());The Apex Flex Queue page in Setup shows held jobs. The Apex Jobs page shows the status and error text of each run.
Summary of design rules
- Keep the number of scheduled jobs small and fixed. Do not create jobs from triggers.
- Give every job a unique, stable name, and check the name before scheduling.
- Pass criteria to the constructor, not record data.
- Never make synchronous callouts in
execute. - Make each run pick up all outstanding work, not only the last interval.
- Log when a cap such as
LIMIT 200is reached. - Stagger start times for jobs that launch batches.
- Plan the abort-deploy-reschedule step before your first release.
Exercise
A scheduled class stores a List<Id> of Account IDs passed to its constructor. Three weeks after scheduling, a developer reports that new accounts are never processed. What is the cause, and how do you fix it?
Show answer
The Schedulable instance is serialized when System.schedule is called, so the ID list is frozen at that moment. Later runs always use the stored list. Fix it by passing criteria (such as a region or a status) to the constructor and querying the matching accounts inside execute. Then abort the old job and schedule the updated class.
Exercise
Your execute method needs to call an external REST API for each of 5,000 records. Which two restrictions apply, and what is the correct structure?
Show answer
A scheduled execute method can't make synchronous callouts, and 5,000 records is more than a single transaction should handle. Have execute call Database.executeBatch with a batch class that implements Database.AllowsCallouts. Each batch chunk then gets its own callout limit, so you can make the calls in chunks of a safe size.
Exercise
A deployment to production fails with an error saying the class has jobs pending or in progress. Name two ways to complete the deployment.
Show answer
Abort the scheduled job, deploy, and schedule it again. Or enable the Deployment Settings option that allows deployments while Apex jobs are pending or in progress, then deploy. Either way, confirm afterward that the job exists in CronTrigger with a future NextFireTime.