Earlier I wrote a blog post dedicated to Asynchronous processing in Salesforce. This time I will focus on Queueable Apex only.
Queueable Apex is a more advanced version of future methods. It has all the functionalities of the future method along with the power of Batch Apex. So –
Queueable Apex = Future Method + Batch Apex
It provides additional job chaining and allows for more complex data types.
With Queueable Apex, developers will be able to submit jobs for asynchronous processing, like something future method can do as well. But the difference comes here –
Flexibility in method parameters: With Queueable Apex, developers will be able to create classes that will allow member variables of non-primitive data types like sObjects or custom Apex types.
Monitor the progress: Once the developer submits a job by executing the command System.enqueuJob, it provides an ID, which is basically a Job Id. With that Id, the developer can now query the progress either from Salesforce interface in the Apex Job page or by querying the AsyncApexJob table.
Chaining jobs: Developer can now chain jobs i.e. starting a new queueable job from an already running queueable job.
Batchable vs Future vs Queueable
Batchable was the first one introduced by Salesforce for asynchronous heavy processing. It was “heavy” in terms of resource usage and also needs longer time to process/complete the work.
To solve the problem with Batchable, Salesforce introduced the Future method. It is lighter on resource and can do all the work which were previously done by Batchable jobs but in a much more efficient way. But the problem with the Future is that it will not return any Job Id, so as a developer, you have no option to figure it out whether the future job is completed or not. At the same time, it has only a limited amount of space to store the data, that is why Future methods only accept Primitive and collections.
To solve the above drawbacks, Salesforce introduced the third version of asynchronous processing i.e. Queueable Apex. It is lighter than Batchable but gives the Job ID, which can be used to know the progress of the job. It also allows developers to pass non-primitive data types. Basically, Queueable is a hybrid solution between the limited future methods and the resource-heavy Batchable interface.
Important points to remember
The execution of a queued job counts once against the shared limit for asynchronous Apex method executions.
You can add up to 50 jobs to the queue in a single transaction.
With chaining, you can start only one job from an already running job. That means there can be only one child job for a parent job. Staring multiple jobs from an already running job is not possible.
There is no depth limit in terms of how deep you can chain jobs. That means you can start a child job from parent one, and then start another job from child one and continue the process unlimited number of times. For developer and trial org, the maximum stack depth for chained job is 5.