3

Per the docs we can only have 100 scheduled apex jobs at any one time in most orgs (5 in dev orgs). Which jobs count towards those limits?

Would the following query return the right number?

SELECT COUNT() FROM CronTrigger 
WHERE CronJobDetail.JobType = '7' 
AND State IN ('WAITING', 'ACQUIRED', 'EXECUTING', 'PAUSED', 'BLOCKED', 'PAUSED_BLOCKED')

Is there dynamic way to retrieve the overall limit so that you don't have to know if you're in a dev org or note and you don't need to update your code as limits increase?

References

You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs.

from Apex Scheduler Docs

Maximum number of Apex classes scheduled concurrently 100. In Developer Edition orgs the limit is 5.

from Apex Governor Limits Docs

2

Your query as is should be just fine, but unless you use a locking statement (FOR UPDATE), it may not include other jobs that are being scheduled the same time your code is running.

There's no API to learn how many open slots you have free/max, but this is one of those cases where you would probably want to use defensive programming instead; you don't need to worry about checking beforehand, and you can still report the error to the user.

Here's a bit of code:

public static String scheduleJobSafe(String jobName, String cron, Schedulable job) {
  try {
    return System.schedule(jobName, cron, job);
  } catch(AsyncException e) {
    return e.getMessage();
  }
}

This method returns a Job ID on success, an error message on failure. You can check which it was:

String response = scheduleJobSafe('123','0 0 0 * * ?', new SomeJobClass());
if(response instanceOf Id) {
  // Success!
} else {
  // Error...
}

If you really wanted to test the current capacity, you could always just call this method in a loop and count your successes. It won't tell you if you're in a Developer Org for sure, but you'd know how many free slots you have, which is arguably better than counting the number of scheduled jobs.

  • thanks for confirming, curious if the locking statement would work on those tables, wouldn't want to block other stuff from getting scheduled. at least in my use case i'm trying to stop scheduling stuff if i'm close to the limit, so a little fuzziness is fine – Ralph Callaway Feb 27 at 0:05
  • @RalphCallaway It's such a rare event in most orgs, I probably wouldn't worry about it. Dev orgs shouldn't be highly scheduled anyways. – sfdcfox Feb 27 at 0:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.