To execute Apex as an asynchronous job, implement the Queueable interface and add the processing logic in your implementation of the execute method.
public class MyQueueableClass implements Queueable {
public void execute(QueueableContext context) { // Your code here }
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:
ID jobID = System.enqueueJob(new MyQueueableClass());
The following are methods for Queueable.
public void execute(QueueableContext context)
Type: Void
public class AsyncExecutionExample implements Queueable { public void execute(QueueableContext context) { Account a = new Account(Name='Acme',Phone='(415) 555-1212'); insert a; } }
ID 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.
AsyncApexJob 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.
@isTest public class AsyncExecutionExampleTest { static testmethod void test1() { // startTest/stopTest block to force async processes // to run in the test. Test.startTest(); System.enqueueJob(new AsyncExecutionExample()); Test.stopTest(); // Validate that the job has run // by verifying that the record was created. // This query returns only the account created in test context by the // Queueable class method. Account acct = [SELECT Name,Phone FROM Account WHERE Name='Acme' LIMIT 1]; System.assertNotEquals(null, acct); System.assertEquals('(415) 555-1212', acct.Phone); } }
The ID of a queueable Apex job isn’t returned in test context—System.enqueueJob returns null in a running test.