Sub topic 1
Where Scheduled Apex fits among asynchronous options
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic Apex classes, methods, and collections.
- Write SOQL queries and run DML statements such as
updateanddelete. - Explain what governor limits are, for example that one transaction can run only a limited number of queries.
- Open Setup and run code in the Developer Console.
You do not need to know any asynchronous Apex yet. This chapter introduces the four options and shows where Scheduled Apex fits among them.
Synchronous and asynchronous execution
Most Apex runs synchronously. A user saves a record, a trigger fires, and the user waits until the code finishes. If the transaction hits a governor limit, the save fails and the user sees the error.
Asynchronous Apex runs later, in a separate transaction. The platform queues the work and runs it when resources are free. This has three practical effects:
- The user does not wait for the work.
- Each asynchronous transaction gets its own governor limits, and some of those limits are higher than the synchronous ones.
- You do not control the exact moment the work starts.
| Limit (per transaction) | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries | 100 | 200 |
| Heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
Salesforce offers four main ways to write asynchronous Apex. Each answers a different question about what starts the work and how much data it handles.
The four options
Future methods
A future method is a static method with the @future annotation. It returns void and accepts only primitive parameters or collections of primitives. Use it for short, one-off work that you want out of the current transaction. Common examples are a callout after a trigger fires, or DML on a setup object that cannot share a transaction with DML on a non-setup object.
Future methods have no job ID you can track. You cannot chain them, and you cannot call one from another future method or from a batch job.
Queueable Apex
A Queueable class implements Queueable and is started with System.enqueueJob. It works like a future method with fewer restrictions. It can hold complex types such as List<Account> as member variables. It returns a job ID. It can also start another queueable job from its own execute method, which is called chaining.
public class RecalculateRatingsJob implements Queueable {
private Set<Id> accountIds;
public RecalculateRatingsJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext qc) {
List<Account> accounts = [
SELECT Id, Rating FROM Account WHERE Id IN :accountIds
];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}Starting it from anonymous Apex looks like this:
Set<Id> ids = new Map<Id, Account>([SELECT Id FROM Account LIMIT 50]).keySet();
Id jobId = System.enqueueJob(new RecalculateRatingsJob(ids));
System.debug('Queued job ' + jobId);Batch Apex
A Batch class implements Database.Batchable<SObject> and is started with Database.executeBatch. It splits a large record set into chunks, called scopes. The default scope is 200 records. The platform runs each scope as its own transaction with fresh governor limits. A batch job can therefore process millions of records that no single transaction could handle.
A batch has three methods:
startdefines the records to process.executeruns once per scope.finishruns once at the end.
Scheduled Apex
A Scheduled class implements Schedulable and has one method, execute(SchedulableContext). You register it with a cron expression, and the platform calls execute at each matching time. Unlike the other three options, nothing in your code or in a user action has to start it. The clock starts it.
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;
}
}You will write and schedule classes like this one in the next chapters. For now, note the shape. The class is short, it has one entry point, and it does one bounded piece of work.
What triggers each option
The four options differ most in what causes them to run, and not in the code they contain.
| Option | Started by | Runs | Typical data volume | Job ID returned |
|---|---|---|---|---|
| Future method | A call from your code | Once, soon | Small | No |
| Queueable | `System.enqueueJob` | Once, soon, can chain | Small to medium | Yes |
| Batch | `Database.executeBatch` | Once, in many transactions | Very large | Yes |
| Scheduled | Cron expression | Repeatedly, or once at a set time | Small, or hands off to Batch | Yes (CronTrigger) |
Future, Queueable, and Batch answer the question "how do I run this work outside the current transaction?" Scheduled Apex answers a different question: "when should this work run?" That difference is why the options combine well. A scheduled job often starts a batch job, because a clock tells you when to begin and a batch tells you how to handle the volume.
When Scheduled Apex is the right choice
Choose Scheduled Apex when the reason to run the code is time, not an event. Typical cases include:
- A nightly cleanup of old records.
- A weekly report that emails a summary to managers.
- A morning job that escalates cases that have been open too long.
- A monthly recalculation of a rollup that is too expensive to maintain in real time.
- A periodic check that pulls data from an external system.
Scheduled Apex is not the right tool when an event should start the work. If a record change should trigger processing, use a trigger and hand heavy work to a Queueable. Polling for changes with a scheduled job adds delay and wastes limits.
Declarative alternatives
You do not always need code. A scheduled-triggered flow can run on a timetable without Apex, and it covers many simple cases such as updating a field on records that match a filter. Prefer a flow when the logic is simple and an admin will maintain it. Prefer Scheduled Apex when you need any of these:
- Complex logic or branching that is awkward in a flow.
- Tight control over query size and DML.
- Reuse of existing Apex services.
- Source-controlled, testable code with a deployment history.
Constraints that shape the design
Scheduled Apex adds a few facts to the usual governor limits. Later chapters cover them in depth, but they affect which option you pick, so read them now.
- Start time is approximate. The platform starts the job when resources are available. It may start after the scheduled minute, so do not write logic that depends on an exact second.
- No synchronous callouts.
executecannot make a synchronous HTTP callout. To call an external service, start a batch class that implementsDatabase.AllowsCallouts, or call a method annotated@future(callout=true). - Limited number of scheduled jobs. An org can hold only a fixed number of scheduled Apex jobs at one time (100 at the time of writing). One class scheduled at five different times counts as five jobs.
- Limits are per execution. Each run of
executeis one transaction. If it queries or updates too many records, it fails like any other transaction. - No user is present. Nobody is there to see an error. A failure is recorded and may send an email, but it never shows a message on screen.
Because of these constraints, the usual pattern is to keep execute very small and move real work elsewhere. The following pair shows it. The scheduled class has no query and no DML. It only starts the batch job.
public class ArchiveOldTasksBatch implements Database.Batchable<SObject> {
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) {}
}
public class NightlyTaskCleanup implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new ArchiveOldTasksBatch(), 200);
}
}In a project, each public class goes in its own file. The batch job processes the records in scopes of 200, and each scope has its own limits. The schedule decides when the cleanup begins, and the batch decides how it is done.
Common mistakes
- Using Scheduled Apex to poll for changes. If you check every five minutes whether something happened, you pay for runs that find nothing and you still react late. Use a trigger and a Queueable instead.
- Doing heavy work directly in
execute. A query for 50,000 records or a loop with DML per record works in a small sandbox and fails in production. Cap the query, or hand the work to Batch Apex. - Choosing a future method when you need a job ID or chaining. Future methods cannot report status and cannot be chained. If you might need either, start with Queueable.
- Assuming exact timing. A job set for 13:00 may begin a little later. Design the logic so that a delayed start does not break it, for example by querying a time window and not "records created in the last 60 seconds."
- Forgetting that jobs count against an org-wide cap. Scheduling the same class many times, for example once per record, exhausts the limit. Schedule one job that processes many records.
- Scheduling without a failure plan. Decide where errors go before launch, whether that is logging to a custom object, an email, or a platform event.
How the pieces fit together
The next chapters build on this picture in a fixed order:
- You write the
Schedulableclass and itsexecutemethod. - You write a cron expression that describes the timetable.
- You register the job with
System.scheduleor from Setup. - The platform stores the job as a
CronTriggerrecord and callsexecuteat each matching time. executeeither does a small piece of work itself or starts Batch Apex.- You monitor and abort the job by querying
CronTrigger, and you test the class withTest.startTestandTest.stopTest.
Scheduling is only the entry point. Most of the reliability of a scheduled job comes from what it starts and how you handle failure.
Exercise
A trigger on Opportunity must call an external pricing service after the record is saved, and it needs the returned job ID so that it can show progress later. Which asynchronous option fits best, and why is Scheduled Apex the wrong choice?
Show answer
Queueable Apex fits best, started with System.enqueueJob. It returns a job ID, accepts complex types, and the work is started by a record event. Scheduled Apex is wrong because the trigger event, not the clock, starts the work. A scheduled job would have to poll for changed records and would react late. The queueable class can make the callout if it implements Database.AllowsCallouts.
Exercise
Every night at 2:00 AM you must delete about 400,000 closed Task records older than a year. Describe which two asynchronous options you combine and what each one does.
Show answer
Use Scheduled Apex and Batch Apex. The Schedulable class has a cron expression for 2:00 AM and a small execute method that calls Database.executeBatch. The Batch class returns a QueryLocator for the old closed tasks in its start method and deletes each scope in its execute method. Each scope of up to 200 records runs in its own transaction with fresh governor limits, so 400,000 records never hit a single-transaction limit.