Sub topic 1
Why Asynchronous Apex: Separate Transactions and Fresh Limits
Prerequisites
Assume you know basic Apex classes, SOQL, DML, governor limits, and @IsTest. A transaction is one unit of Salesforce work. An asynchronous job runs later in a separate transaction, so it gets a fresh set of transaction limits.
Use asynchronous Apex when work is slow, callouts are required, or the current transaction should finish quickly. Queueable Apex is a class-based asynchronous mechanism that can carry state and start another queueable job.
Writing a Queueable Class
A queueable class implements Queueable and defines execute. Member variables hold the serialized state that Salesforce stores until the job runs.
public class AccountRatingJob
implements Queueable, Database.AllowsCallouts {
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 accountRecord : accounts) {
accountRecord.Rating = 'Hot';
}
update accounts;
// A callout can be made here because the class allows callouts.
}
}Database.AllowsCallouts is a marker interface. It permits HTTP or web-service callouts from the queueable transaction. Perform the callout before DML when the same transaction needs both operations.
Enqueuing and Monitoring
Call System.enqueueJob to submit the job. The method returns an ID for the AsyncApexJob record.
Id jobId = System.enqueueJob(
new AccountRatingJob(new List<Id>{ accountId })
);
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob
WHERE Id = :jobId
];The job may still be queued when you query it. Monitoring code should handle statuses such as Queued, Processing, Completed, and Failed.
Chaining Jobs
A queueable can enqueue another queueable from execute. This lets each transaction process a bounded slice and pass the remaining IDs through the next job.
if (!remainingIds.isEmpty()) {
System.enqueueJob(new AccountRatingJob(remainingIds));
}Use chaining deliberately. Each child job creates another asynchronous transaction, and platform limits restrict how many jobs can be enqueued in different contexts.
Exercise
Why does a queueable job receive fresh governor limits?
Show answer
It runs in a separate transaction from the code that enqueued it.