Asynchronous Apex
Published: 2021-04-16 14:06:46

Execution in Background
4 Ways to achieve

**Queueable Apex** 
   For long jobs, if want to use id., chain jobs, use interface to add jobs to the queue and with id monitor them. Advance version of future method
**Schedulable apex:**
   to run on specific Schedule.
**Batch apex:**
   For long jobs that need to performed in batches
**Future method:**
This is useful in making external callouts and easier to use with synchronus process. But having limitations.

**Queueable vs Future method:**
*Both are similar but queueable have additional advantage of ID, hence can be monitored.
*Queueable class can contain non Primitive datatypes such as Sobjects or custom Apex types
*Advantage of chaining jobs

**Queueable Apex Example:**
*Implementation
```
public class AsyncExecutionExample implements Queueable {
    public void execute(QueueableContext context) {
        Account a = new Account(Name='Acme',Phone='(415) 555-1212');
        insert a;        
    }
}
```

*To add job in queue call the method
```
ID jobID = System.enqueueJob(new AsyncExecutionExample());
```

*To check status
```
AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
```

* To chain Jobs: Use system.enqueueJob(new class method());
```
public class AsyncExecutionExample implements Queueable {
    public void execute(QueueableContext context) {
        // Your processing logic here       
        // Chain this job to next job by submitting the next job
        System.enqueueJob(new SecondJob());
    }
}
```

*Only one child job in chaining.
*No limit on number of chains, however limited to 5 in developer and Trail org.
*Max 50 jobs can be added to queue in single txn, however with system.enqueue only 1 can added.

**Schedulable Apex**
[Link](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm)

*Use the Test methods startTest and stopTest around the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. 

*Limit of scheduled jobs = 100 at a time

**Batch Apex**
For large amount of data and break them into chuncks
Max 5 queued or active batch jobs at a time.

**How:**
write an Apex class that implements the Salesforce-provided interface Database.Batchable and then invoke the class programmatically.

Must have 3 methods
1.start method:
```
public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
```
2.Execute method:
```
public void execute(Database.BatchableContext BC, list<P>){}
```
3.finish method:
```
public void finish(Database.BatchableContext BC){}
```

*For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.

[Link](https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_batch_interface.htm)

**Future Method**
To define a future method, simply annotate it with the future annotation, as follows. Methods with the future annotation must be static methods, and can only return a void type. 
*Cannot take Sobjects or objects as arguments
```
global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}
```