Sub topic 2
Writing your first Queueable class
A Queueable class is Apex code that runs later, in its own transaction, after you enqueue it. This chapter shows how to write one, enqueue it, and check that it works. It assumes you know basic Apex syntax and classes, governor limits and transactions, SOQL and DML, and how to write an @IsTest class.
Why use a Queueable
A queueable job runs in a separate transaction from the code that enqueued it. That transaction gets its own governor limits. Asynchronous limits are higher than synchronous ones. For example, the heap size is 12 MB instead of 6 MB, and the SOQL query limit is 200 instead of 100.
Use a queueable when work is too heavy for the current transaction, or when it should not delay the user. Later chapters cover chaining, finalizers, and how to choose between the async tools.
The two parts of a queueable
A queueable class does two things:
- It implements the
Queueableinterface. - It defines an
execute(QueueableContext context)method that holds the work.
Input goes through the constructor and is stored in member variables. The execute method takes no custom arguments, so anything the job needs must already be on the instance when you enqueue it.
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;
}
}The constructor runs in the enqueuing transaction. execute runs later, in the new transaction. The job queries the accounts again inside execute, so it works with current data and not a stale copy.
Enqueuing the job
System.enqueueJob takes an instance of your class. It returns the job ID, which is the ID of an AsyncApexJob record.
Id jobId = System.enqueueJob(new AccountRatingJob(accountIds));
System.debug('Enqueued job ' + jobId);Enqueuing does not run the job. It places the job in the queue, and the platform starts it when resources are available. The job might start within seconds or after a longer wait, so do not write code that depends on it having finished.
Common errors
- Expecting the result immediately. Code after
System.enqueueJobruns before the job does. Do not read the updated records on the next line. - Passing data the job cannot hold. Member variables are serialized when the job is enqueued. Keep them to simple types, collections, and sObjects. The next chapter covers this in detail.
- Enqueuing too many jobs in one transaction. A synchronous transaction can enqueue up to 50 jobs. Enqueue one job that handles a list instead of one job per record.
- Forgetting that
executeneeds a fresh query. If you store sObjects in a member variable, they may be out of date by the time the job runs. Storing IDs and querying again is safer.
Exercise
Exercise
A trigger calls System.enqueueJob(new AccountRatingJob(ids)) and then immediately queries the accounts to check their Rating. The query shows the old value. Why, and what should you do?
Show answer
The job has only been queued. It runs later in a separate transaction, after the trigger's transaction ends, so the Rating has not changed yet. Do not read the result in the same transaction. Check it after the job completes, for example by monitoring the AsyncApexJob record, or write a test that wraps the enqueue in Test.startTest() and Test.stopTest(), which makes the job run before your assertions.