Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. These may be “outside” events such as the arrival of signals, or actions instigated by a program that take place concurrently with program execution, without the program blocking to wait for results.

Three reasons behind using asynchronous programming:

  1. Processing a very large number of records. The limits are higher with asynchronous programming, so if you want to process thousands or millions of records you’ll probably need to use asynchronous.
  2. Making callouts to external web services. Triggers can’t make callouts directly.
  3. Create a better and faster user experience by offloading some processing to asynchronous calls.

Future methods. Changing a method from synchronous to asynchronous processing is amazingly easy. Essentially, you just add the @future annotation to your method. Other than that, just make sure that the method is static and returns only a void type. For example, to create a method for performing a web service callout, we could do something like this:

public class MyFutureClass {
    // Include callout=true when making callouts
    @future(callout=true)    
    static void myFutureMethod(Set ids) {
        // Get the list of contacts in the future method since
        // you cannot pass objects as arguments to future methods
        List contacts = [SELECT Id, LastName, FirstName, Email
            FROM Contact WHERE Id IN :ids];
        // Loop through the results and call a method
        // which contains the code to do the actual callout
        for (Contact con: contacts) {
            String response = anotherClass.calloutMethod(con.Id,
                con.FirstName,
                con.LastName,
                con.Email);
            // May want to add some code here to log
            // the response to a custom object
        }
    }
}

Here we have a class. It has the future callout, indicating that it’s asynchronous? Then it has a method. And it returns a void type as suggested. The method takes an input of the IDs. It creates a list of contacts. There’s a for loop which loops through this list of contacts. I don’t know what string response means.

It says that you can simply call this as you would any other static method. Does this mean you can reference it in other code that you write?

global class MyBatchableClass implements
            Database.Batchable,
            Database.Stateful {  
    // Used to record the total number of Accounts processed
    global Integer numOfRecs = 0;
    // Used to gather the records that will be passed to the interface method
    // This method will only be called once and will return either a
    // Database.QueryLocator object or an Iterable that contains the records
    // or objects passed to the job.            
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, Name FROM Account');                
    }
    // This is where the actual processing occurs as data is chunked into
    // batches and the default batch size is 200.
    global void execute(Database.BatchableContext bc, List scope) {
        for (Account acc : scope) {
            // Do some processing here
            // and then increment the counter variable
            numOfRecs = numOfRecs + 1;
        }     
    }
    // Used to execute any post-processing that may need to happen. This
    // is called only once and after all the batches have finished.
    global void finish(Database.BatchableContext bc) {
        EmailManager.sendMail('someAddress@somewhere.com',
                              numOfRecs + ' Accounts were processed!',
                              'Meet me at the bar for drinks to celebrate');            
    }
}
MyBatchableClass myBatchObject = new MyBatchableClass();
Database.executeBatch(myBatchObject);

Batch apex ^ is used for very large processing jobs. Up to 50 million records?

public class MyQueueableClass implements Queueable {
    private List contacts;
    // Constructor for the class, where we pass
    // in the list of contacts that we want to process
    public MyQueueableClass(List myContacts) {
        contacts = myContacts;
    }
    public void execute(QueueableContext context) {
        // Loop through the contacts passed in through
        // the constructor and call a method
        // which contains the code to do the actual callout
        for (Contact con: contacts) {
            String response = anotherClass.calloutMethod(con.Id,
                    con.FirstName,
                    con.LastName,
                    con.Email);
            // May still want to add some code here to log
            // the response to a custom object
        }
    }
}
List contacts = [SELECT Id, LastName, FirstName, Email
    FROM Contact WHERE Is_Active__c = true];
Id jobId = System.enqueueJob(new MyQueueableClass(contacts));

Queaeuable apex ^ was developed more recently. It accepts non-primitive types such as sObjects. Allows monitoring of the job.

So my understanding is that there are different varieties of asynchronous apex including:

  1. Future methods
  2. Batch Apex
  3. Scheduled apex (similar to batch)
  4. Queueable apex

Seen in this way I can sort of tell what asynchronous is all about. It seems like they are mostly all called near the start of a class. And there are some subtleties you should know about each.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s