Tuesday, November 23, 2010

How to serialize two batch apex

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. We cannot use the "Database.executeBatch(obj)" in finish method of first batch class. Since batch is  a future call so it is not allowed.

The solution is we will have to use the salesforce Email services functionality. Make sure Before creating email services, create Apex classes that implement the Messaging.InboundEmailHandler interface.

global class myHandler 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 for sending a 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 });
    }
    
}
 
Now In email Services handler class You can use
Database.executeBatch(obj);
 
This will make your batch process serialize.