Newer Version Available
Queueable Interface
Namespace
Usage
To execute Apex as an asynchronous job, implement the Queueable interface and add the processing logic in your implementation of the execute method.
1public class MyQueueableClass implements Queueable {1public void execute(QueueableContext context) {
2 // Your code here
3}Your class and method implementation must be declared as public or global.
To submit your class for asynchronous execution, call the System.enqueueJob by passing it an instance of your class implementation of the Queueable interface as follows:
1ID jobID = System.enqueueJob(new MyQueueableClass());Queueable Methods
The following are methods for Queueable.
execute(context)
Signature
public void execute(QueueableContext context)
Parameters
- context
- Type: QueueableContext
- Contains the job ID.
Return Value
Type: Void
Queueable Example Implementation
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.
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}