Monday, July 16, 2018

Apex Asynchronous



An asynchronous process is a process or function that executes a task “in the background” without the user having to wait for the task to finish.

The key benefits of asynchronous processing include:
  • User efficiency
  • Scalability
  • Higher Limits
Asynchronous Apex comes in a number of different flavors.

Types of Asynchronous Apex

Future Apex

  • Future Apex is used to run processes in a separate thread, at a later time when system resources become available.
  • the @future annotation to identify methods that run asynchronously.
  • Callouts to external Web services.
  • If you are making callouts from a trigger or after performing a DML operation, you must use a future or queueable method.
  • A callout in a trigger would hold the database connection open for the lifetime of the callout and that is a “no-no” in a multitenant environment.
  • Future methods must be static methods, and can only return a voidtype.
  • The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
Future Method Syntax
global class SomeClass {
  @future
  public static void someFutureMethod(List<Id> recordIds) {
    List<Account> accounts = [Select Id, Name from Account Where Id IN :recordIds];
    // process account records to do awesome stuff
  }
Sample Callout Code:
  • To make a Web service callout to an external service or API, you create an Apex class with a future method that is marked with (callout=true).
  • The class below has methods for making the callout both synchronously and asynchronously where callouts are not permitted.
public class SMSUtils {
    // Call async from triggers, etc, where callouts are not permitted.
    @future(callout=true)
    public static void sendSMSAsync(String fromNbr, String toNbr, String m) {
        String results = sendSMS(fromNbr, toNbr, m);
        System.debug(results);
    }
    // Call from controllers, etc, for immediate processing
    public static String sendSMS(String fromNbr, String toNbr, String m) {
        // Calling 'send' will result in a callout
        String results = SmsMessage.send(fromNbr, toNbr, m);
        insert new SMS_Log__c(to__c=toNbr, from__c=fromNbr, msg__c=results);
        return results;
    }
}
Test Classes
  • Testing future methods is a little different than typical Apex testing.
  • To test future methods, enclose your test code between the startTest and stopTest test methods.
  • The system collects all asynchronous calls made after the startTest.
  • When stopTest is executed, all these collected asynchronous processes are then run synchronously.
  • You can then assert that the asynchronous call operated properly.
@isTest
global class SMSCalloutMock implements HttpCalloutMock {
    global HttpResponse respond(HttpRequest req) {
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"status":"success"}');
        res.setStatusCode(200);
        return res; 
    }
}
The test class contains a single test method, which tests both the asynchronous and synchronous methods as the former calls the latter.
@IsTest
private class Test_SMSUtils {
  @IsTest
  private static void testSendSms() {
    Test.setMock(HttpCalloutMock.class, new SMSCalloutMock());
    Test.startTest();
      SMSUtils.sendSMSAsync('111', '222', 'Greetings!');
    Test.stopTest();
    // runs callout and check results
    List<SMS_Log__c> logs = [select msg__c from SMS_Log__c];
    System.assertEquals(1, logs.size());
    System.assertEquals('success', logs[0].msg__c);
  }
}

Batch Apex

A developer can now employ batch apex to build complex,long-running processes than run on thousands of records on the Force.com platform.
Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks.
Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits.
Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits.
“If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution.”
Batch Apex Syntax
Batch apex class implement Batchable interface.
eg.
global class batch_Class implement Database.Batchable{
//code here
}

Batch Apex methods

There are three methods.
1. start() :
Breaks data set into batches.
This method is called once at the beginning of a Batch Apex job and returns either a Database.QueryLocator object .
global Database.QueryLocator start(Database.BatchableContext bc){
Databass.getQueryLocator(Query);
}
2. execute() :
Do execution of code in batches.
Performs the actual processing for each chunk or “batch” of data passed to the method. The default batch size is 200 records.
global void execute(Database.BatchableContext con){
}
3. finish() :
anything you want to do once all batches have been processed.
Used to execute post-processing operations (for example, sending an email) and is called once after all batches are processed.
You can put finish() method is as a blank.
global void finish(Database.BatchableContext con){
}
Below video have given best explanation about batch apex.



Write a batch apex program for update fields value.
global class b1 implements Database.Batchable<sObject>
{
 global final String query;
 global final String s_Object;
 global final String field;
 global final String field_value;
 
 global b1(String q,String s,String f,String v)
 {
 query =q;
 s_Object=s;
 field=f;
 field_value=v;
 } 
 global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
  }
 global void execute(Database.BatchableContext BC,List <sObject>    scope){
     for(sObject o:scope){
        o.put(field,field_value);
        update scope;
        }
 }
 global void finish(Database.BatchableContext BC){
 
 }
}
execute in anonymous block in developer console.
String q='Select Description From Account Limit 10';
String e='Account';
String f='Description';
String v='Just got updated';
Id batchInstanceId=Database.executeBatch((new b1(q,e,f,v)));
Reference : Trailhead Salesforce

No comments:

Post a Comment

Apttus CPQ interview questions and answers

1. What is CPQ? A. CPQ stands for Configure, Price and Quote. CPQ is a tool which helps companies produce accurate, configured quotes a...