Queueable jobs are similar to future methods, but they provide you with these additional benefits.
- Getting an ID for your job: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress.
- Using non-primitive types: Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types.
- Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if you need to do some processing that depends on another process to have run first.
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name='Acme',Phone='(415) 555-1212');
insert a;
}
}
To add this class as a job on the queue, call this method:
ID jobID = System.enqueueJob(new AsyncExecutionExample());
Chaining Jobs
To chain a job to another job, submit the second job from the execute() method of your queueable class. You can add only one job from an executing job, which means that only one child job can exist for each parent job. You can refer the code below for chaining jobs:...
...
...
for (Case caseRecord : cases)
caseRecord.Status = 'Closed';
for (Lead lead : leads)
lead.Status = 'Inactive';
Map<Integer, List<sObject>> indexToObjects = new Map<Integer, List<SObject>>();
indexToObjects.put(0, cases);
indexToObjects.put(1, leads);
Integer startingIndex = 0;
System.enqueueJob(new Worker(indexToObjects, startingIndex));
Worker.cls
public without sharing class Worker implements Queueable {
Map<Integer, List<sObject>> indexToObjectUpdates;
Integer index;
public Worker(Map<Integer, List<sObject>> indexToObjectUpdates, Integer index) {
this.indexToObjectUpdates = indexToObjectUpdates;
this.index = index;
}
public void execute(QueueableContext context) {
if (!indexToObjectUpdates.containsKey(index))
return;
update indexToObjectUpdates.get(index);
Integer nextIndex = index + 1;
if (indexToObjectUpdates.containsKey(nextIndex))
System.enqueueJob(new Worker(indexToObjectUpdates, nextIndex));
}
}
Points to remember:
- Apex allows HTTP and web service callouts from queueable and chained queueable jobs, if they implement the Database.AllowsCallouts marker interface.
- You can monitor the status of your job programmatically by querying AsyncApexJob or through the user interface in Setup by entering Apex Jobs in the Quick Find box, then selecting Apex Jobs.