Apex provides four options to run code asynchronously. Future Method, Queueable Apex, Batch Apex and Scheduled Apex.
Future Methods
- Methods are annotated with @future annotation.
- Future methods should be static and can only return void type.
- It supports parameters, but parameters should be primitive data types, arrays of primitive data types, or collection. sObjects or objects cannot be used as parameters to future methods.
- These methods run in their own thread and will only start when the resources are available.
- They are used for long running operations and prevent any delay in apex transaction.
- They can be used for callouts to external web services and also separating DML operations to prevent Mixed DML error.
- Future methods should not be used for processing large amount of data. In that case, Batch Apex should be used.
- To test future methods, enclose test code between startTest and stopTest test methods.
- Future methods not necessarity execute in the same order as they are called.
- Future methods cannot be used inside Visualforce controllers getter, setter, constructor methods.
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_invoking_future_methods.htm
- https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_future_methods
Queueable Apex
- Apex code must implement Queueable interace.
- By implementing Queueable interface, Apex class can be added to the job queue and it will run when the system resources are available.
- The difference between Queueable Apex and Future methods is –
- Queueable Apex supports job-chaining
- It supports non primitive data types likes sObjects or custom objects.
- System.enqueueJob method is used to submit the job. After submission, ID of AsyncApexJob record is returned.
- Using SOQL, status of the queued job can be monitored programmatically by querying AsyncApexJob table. The same is also possible from “Apex Jobs”in setup.
- Chaining is supported here, thus allowing a job to be started from another running job.
- The execution of a queued job counts once against the shared limit for Asynchronous Apex method executions.
- Maximum 50 jobs can be added to the queue in a single transaction.
- Only one child job can exist for each parent job.
- There is no limit on the dept of the chained jobs.
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm
- https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_queueable
Batch Apex
- Apex class must implement Database.Batchable interface, which will allow them to write code against start, execute and finish methods.
- A batch class can be invoked by calling Database.executeBatch. It needs the instance of the class and batch size.
- Using SOQL, status of the batch job can be monitored programmatically by querying AsyncApexJob table. The same is also possible from “Apex Jobs”in setup.
- It is used to process millions of records asynchronously.
- Apex jobs always get executed in a separate transaction.
- Every batch apex transactions has their own governor limit(new limit always). Thus if one batch fails, it will not impact other batches.
- Start Method:
- It is used to collect records or objects which will be passed to the method “execute”.
- It returns either a Database.QueryLocator object or an Iterable.
- Execute Method:
- This method is responsible for doing the actual processing work.
- Default batch size is 200.
- Parameter it needs – a reference to Database.BatchableContext object and a list of sObjects.
- Finish Method:
- This method is used to do post-processing operations likes sending email etc.
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch.htm
- https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_batch
Scheduled Apex
- Apex class must implement Schedulable interface. By implementing this interface, an apex class can be scheduled at specific time/day in the Apex Scheduler.
- System.Schedule method is used to schedule an instance of the class.
- It should implement the execute method(this is the only method). Parameter – SchedulableContext object.
- Once a class is scheduled, as CronTrigger object record is created. The getTriggerId method can be used to return the ID of CronTrigger record.
- If the class is getting scheduled from Trigger, Governor limit should be checked.
- Additional processing should be done in a separate class outside of execute method.
- Maximum 100 scheduled Apex jobs at one time is possible.
- Synchronous Web service callouts are not supported from scheduled apex. To do that, make an asynchronous callout in a method annotated with @future(callout=true) and then call it from scheduled apex. Note – If scheduled apex exceutes batch job, then callouts are possible as they are supported from batch class.