Sub topic 2
Writing your first Queueable class
What you need before you start
This chapter assumes you can read and write basic Apex classes, and that you know governor limits apply per transaction. It also assumes you can write SOQL queries and DML statements and run a test with @IsTest. Earlier chapters explained why asynchronous Apex exists: work runs in a separate transaction with its own set of limits. This chapter builds the smallest useful queueable and explains each piece of it.
What a queueable is
Queueable Apex is a way to run code later, in its own transaction. You write a class that implements the Queueable interface. You create an instance and hand it to the platform with System.enqueueJob. The platform puts the job in a queue and runs it when a worker is free. This usually takes seconds, but Salesforce makes no promise about timing.
A queueable has three parts:
- The class declaration,
implements Queueable. - A constructor and member variables that carry the input.
- An
execute(QueueableContext context)method that does the work.
The first example
public class AccountRatingJob implements Queueable {
private List<Id> accountIds;
public AccountRatingJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}
// Enqueue from any Apex code:
// Id jobId = System.enqueueJob(new AccountRatingJob(accountIds));Read the class from top to bottom.
implements Queueableis the contract. The interface has one method,execute.accountIdsis a member variable. The platform serializes it when you enqueue the job and restores it beforeexecuteruns. The next chapter covers what can and cannot be stored there.- The constructor is how the caller passes input.
executetakes no arguments except the context, so everything the job needs must already be in the object. executeruns in a new transaction. It has its own SOQL, DML, and CPU budget, separate from the code that enqueued it.
The class does one bulk query and one bulk DML statement, so it respects governor limits in the same way synchronous code does.
What happens when you enqueue
System.enqueueJob does not run execute. It saves the serialized object, creates a job record, and returns the job ID right away. The calling code keeps going. execute runs later, in another transaction.
Three consequences follow from this model.
- The job starts only if the caller's transaction commits. If the caller throws an unhandled exception and rolls back, the enqueue is rolled back too, and the job never runs.
- The job sees committed data. It reads whatever is in the database when it starts, which may differ from what the caller held in memory.
- The caller cannot get a return value. The job ID is the only thing you get back. To learn the outcome you must monitor the job or have the job write its result somewhere.
The QueueableContext
The context argument has one method, getJobId(). It returns the ID of the currently running job, which is the same value System.enqueueJob returned to the caller. Use it for logging or to correlate a job with its AsyncApexJob record.
public class LoggedJob implements Queueable {
public void execute(QueueableContext context) {
System.debug('Running job ' + context.getJobId());
}
}A later chapter shows how to query AsyncApexJob with this ID.
Where you can enqueue from
You can call System.enqueueJob from triggers, controllers, other Apex classes, anonymous Apex, and from inside another queueable. Enqueuing from a trigger is common, because a trigger often needs to do work that does not belong in the saving transaction.
trigger AccountTrigger on Account (after update) {
List<Id> changedIds = new List<Id>();
for (Account a : Trigger.new) {
if (a.Rating != Trigger.oldMap.get(a.Id).Rating) {
changedIds.add(a.Id);
}
}
if (!changedIds.isEmpty()) {
System.enqueueJob(new AccountRatingJob(changedIds));
}
}The trigger collects all the IDs first and enqueues one job for the whole batch of records. It does not enqueue inside the loop.
Queueable compared with a future method
Queueable is the newer tool and replaces most uses of @future.
| Feature | `@future` method | Queueable class |
|---|---|---|
| Parameters | Primitives and collections of primitives only | Any serializable type, including sObjects and custom classes |
| Returns a job ID | No | Yes |
| Can chain a follow-up job | No | Yes |
| Can be monitored by ID | Hard | Yes, through `AsyncApexJob` |
| Can attach a finalizer | No | Yes |
The ability to hold sObjects and your own types in member variables is the main reason to prefer queueable. A later chapter in this tutorial compares all the options, including Batch Apex.
Limits worth knowing now
Later chapters cover limits in detail. These are enough to write a first job safely.
- A synchronous transaction can enqueue up to 50 queueable jobs.
- A running queueable can enqueue only one child job. This is what makes chaining possible.
- The job runs with asynchronous limits. These are higher than synchronous limits for some resources, such as heap size (12 MB instead of 6 MB) and CPU time (60,000 ms instead of 10,000 ms). The SOQL query limit is 200 in async context.
- A job that needs to make HTTP callouts must also implement
Database.AllowsCallouts. Without it, the callout fails at run time.
Common mistakes
- Expecting the job to run immediately.
enqueueJobreturns beforeexecutestarts. Code after it cannot rely on the job's results. - Passing too much state. Everything in the member variables is serialized. Large lists of full sObjects use heap in the enqueuing transaction and again in the job. Passing a list of IDs and querying inside
executeis smaller, and the data is fresher. - Assuming the data is unchanged. Between enqueue and run, another user or process may change a record. If your logic depends on a field value, re-query it in
execute. - Ignoring bulk behavior. A trigger enqueues once per transaction chunk. Write the job to handle a list, not a single record.
- Putting DML before a callout. A transaction cannot make a callout after uncommitted DML. This applies inside
executeas well. - Letting an exception go unhandled. An unhandled exception fails the job, rolls back its DML, and sends a failure email to the user who started it. The caller is not told. Finalizers, covered in a later chapter, are the tool for reacting to this.
Testing the basic job
Jobs enqueued in a test do not run until the test asks them to. Wrap the enqueue in Test.startTest() and Test.stopTest(). When stopTest is called, the platform runs the queued job synchronously, and the assertions after it can check the result.
@IsTest
private class AccountRatingJobTest {
@IsTest
static void setsRatingToHot() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
System.enqueueJob(new AccountRatingJob(new List<Id>{ a.Id }));
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];
System.assertEquals('Hot', result.Rating);
}
}Two details matter here. Without startTest and stopTest, the job may never run, and the assertion fails with the original value. Also, the insert happens before startTest, so the setup work does not count against the limits of the code under test.
Design checklist
Before you ship a first queueable, check these points:
- The constructor receives the minimum input, preferably IDs.
executeis bulk-safe and re-queries anything that could have changed.- The caller enqueues once per transaction, not once per record.
- The class implements
Database.AllowsCalloutsonly if it makes callouts. - One test enqueues the job between
startTestandstopTestand asserts on the outcome.
Exercise
A trigger on Contact runs after insert with up to 200 records. A developer writes a for loop over Trigger.new that calls System.enqueueJob(new ContactJob(c.Id)) for each contact. What goes wrong, and how do you fix it?
Show answer
A synchronous transaction can enqueue at most 50 queueable jobs, so inserting 200 contacts throws a limit exception on the 51st enqueue. Fix it by collecting the IDs into a List<Id> in the loop and calling System.enqueueJob once, with a ContactJob whose constructor takes the list and whose execute method processes all the records in bulk.
Exercise
A test enqueues AccountRatingJob, then immediately queries the account and asserts that Rating equals 'Hot'. The assertion fails. Why, and what is the fix?
Show answer
The job has not run yet, because enqueued jobs execute asynchronously and, in a test, only run when Test.stopTest() is called. Put the System.enqueueJob call between Test.startTest() and Test.stopTest(), and run the query and assertion after stopTest().