Queueable Apex vs Batch Apex | Salesforce Developer Guide
Queueable Apex
Apex processes that run for a long time, such as extensive database operations or external web service callouts, can be run asynchronously by implementing the Queueable interface and adding a job to the Apex job queue.
Queueable jobs:
- Getting an ID for the job
- Using non-primitive types
- Can do 50 chaining jobs (one queue can call to another queue)
Queueable Syntax
public class TestDemoQueueable implements Queueable {
public void execute(QueueableContext qCntxt) {
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 = [Method] System.enqueueJob(new TestDemoQueueable()); //Instantiate
[Method] can be called from the anonymous window and other classes & Triggers.
Governor limit is 10k record DML updates in one transaction.
AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
Chaining:
public class FirstQueueableclsExample implements Queueable{
public void (QueueableContext context){
//further processing.
System.enqueueJob(new SecondJob()); //chaining of Jobs.
}
}
Example: Create Contact with Name for Account created
Don't forget to check out: Callouts from Batch Apex and Calling One Batch Apex to Another Batch | Salesforce Tutorial Guide
Queueable Class
public class ContactCreationQueueable implements Queueable{
private List<Account> accListToCreateContacts;
public ContactCreationQueueable(List<Account> expectingAccountFromTrigger){
this.accListToCreateContacts=expectingAccountFromTrigger;
}
public void execute(QueueableContext qCntxt){
List<Contact> contactToUpdate =new List<Contact>();
//Loop on all accounts that are inserted.
for(Account acc:accListToCreateContacts){
Contact con= new Contact();
con.LastName=acc.Name;
con.AccountId=acc.Id;
contactToUpdate.add(con); //Add each Contact to List
}
if(contactToUpdate.size()>0){
Insert contactToUpdate;
}
}
}
Trigger
trigger AccountTriggerQueue on Account (after insert) {
if(Trigger.isAfter && Trigger.isInsert){
system.enqueueJob(new ContactCreationQueueable(Trigger.new)); //Chaining
}
}
Limitation
- Queueable can't handle millions of records in one job.
- Only one job can be scheduled at a time.
- In the developer edition stack depth for chaining the jobs is limited to 5 including the parent job.
Batch Apex
- Batch apex is used to run large jobs (like millions) that would exceed normal processing units.
- Using Batch apex, we can process records asynchronously in batches.
- Batch apex processes up to 50million records in the background, unlike Future and Queueable.
Batch Apex Syntax
public class MyClass implements Database.Batchabale{
Start(){
//Query all the records to process.
}
Execute(){
//Process batch of records from the start.
Finish(){
//Any post processing logic Eg:send Mail
}
}
}
Batch apex methods:
- Start().
- Execute().
- Finish().
How Batch Apex Works
Start(): query all records :lets say 100000 [Sends 2000 records every time(Maximum BatchSize)]
Execute(): going to process 20000 records only
Finish(): Post-Processing and another task like sending mail or handling exception.
Batch Size
- Minimum batch size -1
- Maximum batch size -2000
- Default will be -200
Way of Calling:
Database.executeBatch=(new MyClass(),2000); ExampleBatchClass myBatchObject = new ExampleBatchClass(); Id batchId = Database.executeBatch(myBatchOBject);
Example:
public class TestDemoBatch implements Database.Batchable<Sobject>{
public Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator('Select Id, name from Account');
}
public void execute(Database.BatchableContext bc , List<Account> subListFromStartMethod){
for(Account acc:subListFromStartMethod){
acc.Name='Demo Batch-'+acc.Name;
}
UPDATE subListFromStartMethod;
}
public void finish(Database.BatchableContext bc){
System.debug('@@Post Processing Done');
Database.execute(new BatchClass2()); //Chaining of Batch Jobs
}
}
Check out an amazing Salesforce video tutorial here: Apex Scheduler in Salesforce | Asynchronous Apex
Batch Apex over Queueable
- It allows the processing 50million of records in the background
- Best suitable for long-running processes
Limitation
- Can have only 5 batch jobs running at a time.
- Execution may be delayed due to server availability.
- @Future methods are not allowed.
- Future methods cannot be called from Batch Apex.
Using Queueable Over Batch Apex:
- A future method runs in the background, asynchronously. We can call a future method for executing long-running operations, such as callouts to external web services or other operations, on its own time as we can't call future methods from the batch class.
- It comes in handy when we need to have both the operations of Batch and Future method and it should implement Queueable Interface.
- Queueable apex can be called from the Future and Batch class.
- Moreover Queueable apex supports getContent/getContentAsPDF() method.
- In Queueable apex, we can chain up to 50 jobs and in developer edition, we can chain up to 5 jobs only whereas in BatchApex 5 concurrent jobs are allowed to run at a time.
Responses