I want to run 2 batch jobs in series i.e. 2nd batch should start running just after 1st batch finishes. Can I do that?
3 Answers
Yes you can do this. As of Winter '12 (api v26) a new feature was added to allow daisy chaining of batch jobs by providing the ability to call the executeBatch method from the finish method.
One thing to be wary of with this approach is the number of batch slots you have available (max 5 jobs running at one time), check first there is space to run your job and if not scheduled to run again in a minute (you should perform the same check in your schedule job too). See example below:
// finish by sending email to specified recipeint, or job creator if not set
global void finish(Database.BatchableContext BC)
{
AsyncApexJob batchJob = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
sendEmail( batchJob.CreatedBy.Email );
Integer jobs = [Select count() From AsyncApexJob Where JobType = 'BatchApex' and ( Status = 'Queued' or Status = 'Processing' or Status = 'Preparing' )];
if( jobs > 4 )
{
// try again in a minute
Datetime sysTime = System.now().addSeconds( 60 );
String chronExpression = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
EmailInvoicesBatch scheduledBatch = new EmailInvoicesBatch();
System.schedule( 'EmailInvoicesBatchSchedule ' + sysTime, chronExpression, scheduledBatch );
}
else
{
EmailInvoicesBatch batch = new EmailInvoicesBatch();
Database.executeBatch( batch, 1 );
}
}
-
-
Yes great answer Phil! One thing to keep in mind is the error handling and recovery aspects of Batch Apex solutions, while this is a great new feature it does add extra responsibility and consideration. I wrote a blog post on this around the time this feature came out. Might be of use to you to consider these things. andrewfawcett.wordpress.com/2012/10/14/… Feb 6, 2013 at 10:12
-
-
Use System.scheduleBatch instead of System.schedule to avoid your batch class having to implement also the schedulable interface. In addition, you avoid having to create the cron expression, as you can pass it the number of minutes from now to run it at.– ceiroaJul 18, 2014 at 20:13
-
I've always found it safer to roll my own, not sure how reliable scheduleBatch is salesforce.stackexchange.com/questions/12794/… Jul 19, 2014 at 8:47
You can invoke the second job by calling Database.executeBatch from the finish method of the first job.
You call the second batch from finish method of first one .Make sure you have an API of 26 and above for your class