Below is an example of how to implement the Queueable interface.
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name='Acme',Phone='(415) 555-1212');
insert a;
}
}
You can add the class to a job queue by calling this method.
ID jobID = System.enqueueJob(new AsyncExecutionExample());
If you have a second class that also implements the Queueable interface and you want it to run after the class above is done, you can chain them together like this:
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name='Acme',Phone='(415) 555-1212');
insert a;
// Chain this job to next job by submitting the next job
System.enqueueJob(new SecondJob());
}
}
And here is list of limits from Queueable Apex vs Future methods
| Queueble | Future Methods |
|---|---|
| The execution of a queued job counts once against the shared limit for asynchronous Apex method executions. | Same |
| You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction. | No more than 50 method calls per Apex invocation. |
| The maximum stack depth for chained jobs is two, which means that you can have a maximum of two jobs in the chain. | A future method can’t invoke another future method. |
| When chaining jobs, you can add only one job from an executing job with System.enqueueJob. | Methods with the future annotation cannot take sObjects or objects as arguments. |
These are just the limits from the Salesforce release notes. I haven't had a chance to play much with the Queueable interface, since it just came out in the Winter'15, so I haven't discovered some other limits yet. When I find some new issues with the Queueable interface, I will post them in another blog post. Stay tune!