how to avoid concurrent batch jobs running in salesforce

1,041 views
Skip to first unread message

Prabhakar Chimakurthy

unread,
Feb 19, 2014, 1:48:13 PM2/19/14
to salesforce-p...@googlegroups.com

Description

- Batch Apex can have 5 concurrent (simultaneous) jobs running in parallel.
- That is, explicitly, the number of Batch Apex jobs whose status in the AsyncApexJob table are 'Processing' or 'Preparing'.
- A job is not executing when in Queued or any other status.

- Scheduling more than 5 Batch Apex jobs returns the error "Attempted to schedule too many concurrent batch jobs in this org"
- You may sometimes receive a Developer script exception e-mail when this limit is reached, but not always. (This is also by design).

- You may attempt to use the following code sample to avoid encountering this limit, particularly if the batch is executed in a scheduled class.

Resolution

- Count how many current jobs are being executed.
- This information is stored in the AsyncApexJob table.
- Before calling the Database.executebatch() method within a scheduled class, you should try something like:

//check if there are 5 active batch jobs
if ([SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex' AND (Status = 'Processing' OR Status = 'Preparing')] < 5]){
   Database.executeBatch(batchClassInstance);
} else {
   //schedule this same schedulable class again in 30 mins
   nameOfYourSchedulableClass sc = new nameOfYourSchedulableClass();
   Datetime dt = Datetime.now() + (0.024305); // i.e. 30 mins
   String timeForScheduler = dt.format('s m H d M \'?\' yyyy');
   Id schedId = System.Schedule('MatrixRetry'+timeForScheduler,timeForScheduler,sc);
}

- In the same 'else' clause you can send an e-mail to yourselves so you're notified that the job will run a bit later than normal.

Note:

- You can have more than 5 scheduled classes that will call Database.executeBatch() in a Queued status


--
Thanks & Regards,
Prabhakar Chimakurthy.

Ravindra Babu Nagaboina

unread,
Feb 20, 2014, 5:56:18 AM2/20/14
to salesforce-p...@googlegroups.com
Good one, Prabhakar.


--
You received this message because you are subscribed to the Google Groups "salesforce professionals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to salesforce-profess...@googlegroups.com.
To post to this group, send email to salesforce-p...@googlegroups.com.
Visit this group at http://groups.google.com/group/salesforce-professionals.
For more options, visit https://groups.google.com/groups/opt_out.



--
Thanks & Regards.
Ravindra Babu Nagaboina


Reply all
Reply to author
Forward
0 new messages