What is Asynchronous Apex?

Asynchronous Apex is used to run the code in a separate thread.

Even after following all the best practices, there is a chance that we could hit the governor limits in Salesforce. So, to avoid this scenario we can use Asynchronous Apex.

With Asynchronous Apex the code runs on its own time.

We can write Asynchronous Apex in the following ways:

  1. Future Methods
  2. Batch Apex
  3. Queueable Apex
  4. Scheduled Apex

Future Methods

Future Method is the easiest one to implement among the rest. All you have to do is attach @future at the beginning of a method and you are good to go.

public class className{
    @Future
    public static void methodName(List<Id> recordIds){
        //Logic
    }
}

When to use Future Method?

Note:

  1. Future methods can not be called from a future method.
  2. To allow Callouts use @future(callout=true).
  3. sObjects can not be passed to future methods.

Batch Apex

To use Batch Apex you need to implement the Database.Batchable interface.

It is necessary to implement the Start, Execute, and Finish methods in a Batch Class.

The Start method is supposed to retrieve the records that will be processed in the Execute method.

The Execute method then receives a batch of records as the scope and all the logic is applied here.

Finally, we have the finish method, which is executed after all the batches have finished running.

public class batchClass implements Database.Batchable<sObject>{

    public final String Query;

    public batchClass(String q){
        Query = q;
    }

    public Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext BC, List<sObject> scope){
        for(sobject s : scope){
            s.put(Field,Value); 
        }
        update scope;
    }

    public void finish(Database.BatchableContext BC){
        //Finish Code
    }
}

Now to run the Batch Class you can use the Database.executeBatch method. The first parameter in this method is a new instance of the batch class and the second parameter is the batch size.

If you do not mention the batch size, then the batch runs with the default batch size of 200.

Database.executeBatch(new batchClass(), 100);

Note:

  1. To allow the use of Callouts from the batch class, add Database.AllowCallouts in the class definition.
  2. Each Execution of a batch job is a separate transaction. Use Database.Stateful in the class definition to retain the value of non-static variables across separate transactions. It is used for counting records or summarizing records as they are processed.

Queueable Apex

To use Queueable Apex you need to implement the Queueable Interface.

Queueable Apex is a mixture of Batch Apex and Future Methods.

It needs only one Execute method which has a parameter of QueueableContext.

public class queueableClass implements Queueable {
    public void execute(QueueableContext context) {
        // Logic      
    }
}

To execute a Queueable Class you need to use System.enqueueJob method.

System.enqueueJob(new queueableClass());

Notes:

  • You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
  • There is no limit enforced for chaining jobs. But in the developer sandbox, we can only chain upto 5 jobs.
  • To allow callouts from QueueableContext use Database.allowCallouts in the class definition.

Scheduled Apex

Scheduled Apex is used to run specific pieces of code at a certain time and date. So you need to implement the Schedulable Interface, which calls the other class.

public class testSchedule implements Schedulable{
    public void execute(SchedulableContext SC){
        //Code
    }
}

To Schedule this class you can use the System.Schedule method. The first parameter here is a title for the Scheduled Job. The second parameter is the exact timing and date when the class will run. The third parameter is the name of the Scheduled Class.

System.schedule('Scheduled Job', '20 30 8 10 2 ?', new testSchedule());

Notes:

  • You can also schedule a batch job using Schedulable Interface. But the easier way is to use the System.ScheduleBatch method.