top of page

Asynchronous Apex - Part 1

Apex offers multiple ways for running your Apex code asynchronously. Choose the asynchronous Apex feature that best suits your needs.

Below table lists the asynchronous Apex features and when to use each.

Future Methods

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time.

You can also use future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available.

  • 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 necessarily execute in the same order as they are called.

Queueable Apex

  • Apex code must implement Queueable interface.

  • 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, the 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 depth of the chained jobs.

53 views0 comments

Recent Posts

See All

Asynchronous Apex - Part 2

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.execu


bottom of page