Newer Version Available
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. In this way, your asynchronous Apex job runs in the background in its own thread and doesn’t delay the execution of your main Apex logic. Each queued job runs when system resources become available. A benefit of using the Queueable interface methods is that some governor limits are higher than for synchronous Apex, such as heap size limits.
- Getting an ID for your job: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. Use this ID to identify and monitor your job, either through the Salesforce UI (Apex Jobs page), or programmatically by querying your record from AsyncApexJob.
- Using non-primitive types: Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
- Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if your process depends on another process to have run first.
Example
1public class AsyncExecutionExample implements Queueable {
2 public void execute(QueueableContext context) {
3 Account a = new Account(Name='Acme',Phone='(415) 555-1212');
4 insert a;
5 }
6}1ID jobID = System.enqueueJob(new AsyncExecutionExample());After you submit your queueable class for execution, the job is added to the queue and will be processed when system resources become available. You can monitor the status of your job programmatically by querying AsyncApexJob or through the user interface in Setup by entering Apex Jobs in the Quick Find box, then selecting Apex Jobs.
To query information about your submitted job, perform a SOQL query on AsyncApexJob by filtering on the job ID that the System.enqueueJob method returns. This example uses the jobID variable that was obtained in the previous example.
1AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];Similar to future jobs, queueable jobs don’t process batches, and so the number of processed batches and the number of total batches are always zero.
Adding a Scheduled Delay to Queueable Jobs
Use the System.enqueueJob(queueable, delay) method to add queueable jobs to the asynchronous execution queue with a specified minimum delay (0–10 minutes). The delay is ignored during Apex testing.
See enqueueJob(queueable, delay) in the Apex Reference Guide.
- If the external system is rate-limited and can be overloaded by chained queueable jobs that are making rapid callouts.
- When polling for results, and executing too fast can cause wasted usage of the daily async Apex limits.
This example adds a job for delayed asynchronous execution by passing in an instance of your class implementation of the Queueable interface for execution. There’s a minimum delay of 5 minutes before the job is executed.
1Integer delayInMinutes = 5;
2ID jobID = System.enqueueJob(new MyQueueableClass(), delayInMinutes);Admins can define a default org-wide delay (1–600 seconds) in scheduling queueable jobs that were scheduled without a delay parameter. Use the delay setting as a mechanism to slow default queueable job execution. If the setting is omitted, Apex uses the standard queueable timing with no added delay.
- From Setup, in the Quick Find box, enter Apex Settings, and then enter a value (1–600 seconds) for Default minimum enqueue delay (in seconds) for queueable jobs that do not have a delay parameter
- To enable this feature programmatically with Metadata API, see ApexSettings in the Metadata API Developer Guide.
Testing Queueable Jobs
1@isTest
2public class AsyncExecutionExampleTest {
3 static testmethod void test1() {
4 // startTest/stopTest block to force async processes
5 // to run in the test.
6 Test.startTest();
7 System.enqueueJob(new AsyncExecutionExample());
8 Test.stopTest();
9
10 // Validate that the job has run
11 // by verifying that the record was created.
12 // This query returns only the account created in test context by the
13 // Queueable class method.
14 Account acct = [SELECT Name,Phone FROM Account WHERE Name='Acme' LIMIT 1];
15 System.assertNotEquals(null, acct);
16 System.assertEquals('(415) 555-1212', acct.Phone);
17 }
18}Chaining Jobs
To run a job after some other processing is done first by another job, you can chain queueable jobs. To chain a job to another job, submit the second job from the execute() method of your queueable class. You can add only one job from an executing job, which means that only one child job can exist for each parent job. For example, if you have a second class called SecondJob that implements the Queueable interface, you can add this class to the queue in the execute() method as follows:
1public class AsyncExecutionExample implements Queueable {
2 public void execute(QueueableContext context) {
3 // Your processing logic here
4
5 // Chain this job to next job by submitting the next job
6 System.enqueueJob(new SecondJob());
7 }
8}You can’t chain queueable jobs in an Apex test. Doing so results in an error. To avoid getting an error, you can check if Apex is running in test context by calling Test.isRunningTest() before chaining jobs.
Queueable Apex Limits
- The execution of a queued job counts one time against the shared limit for asynchronous Apex method executions. See Lightning Platform Apex Limits.
- You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction. In asynchronous transactions (for example, from a batch Apex job), you can add only one job to the queue with System.enqueueJob. To check how many queueable jobs have been added in one transaction, call Limits.getQueueableJobs().
- Because no limit is enforced on the depth of chained jobs, you can chain one job to another. You can repeat this process with each new child job to link it to a new child job. For Developer Edition and Trial organizations, the maximum stack depth for chained jobs is 5, which means that you can chain jobs four times. The maximum number of jobs in the chain is 5, including the initial parent queueable job.
- When chaining jobs with System.enqueueJob, you can add only one job from an executing job. Only one child job can exist for each parent queueable job. Starting multiple child jobs from the same queueable job isn’t supported.