Showing posts with label Batch Apex - Salesforce. Show all posts
Showing posts with label Batch Apex - Salesforce. Show all posts

Tuesday, March 22, 2011

Serialize Batch apex in Salesforce

In salesforce we cannot call a batch apex class from another batch apex class because batch apex is a future call.

To make the batch process serialize we have to start the another batch when first batch is finished. By using salesforce Email services we can make batch process serializable. Create a class which implements Messaging.InboundEmailHandler.

global class EmailServiceHandler implements Messaging.InboundEmailHandler 
{
        global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,Messaging.InboundEnvelope envelope) 
        {
  Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
  return result;
 }
}

Now create a class to send an email to salesforce email services email address.

public class EmailHandler
{
    public static void sendEmail(string body)
    {
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       String[] toAddresses = new String[] {'myhandler@74m9vxsizy32oug74yh6rhj7e.in.salesforce.com'};
       mail.setToAddresses(toAddresses);
       mail.setSubject('Test Batch' );
       mail.setPlainTextBody(body);
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
}

When first batch apex is finished. We will have to call sendEmail method of EmailHandler class in finish method of batch class.

EmailHandler.sendEmail('start second batch');

In the EmailServiceHandler class we can check the email body.
global class EmailServiceHandler implements Messaging.InboundEmailHandler 
{
        global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,Messaging.InboundEnvelope envelope) 
        {
    if (email.plaintextbody == 'start second batch')
           {
              // create the instance of second batch class
              SecondBatchClass obj = new SecondBatchClass();
              Database.executeBatch(obj);
           } 
           Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    return result;
 }
}


This will make your batch process serialize.