Jul 15, 2013

Schedule Batch Apex in Summer '13

You could always schedule a Batch Apex before Summer '13.  Though, a new system method in this release did make it significantly easier to do.

Previously, I would create my batch class, with its batchable interface declared and its start, execute, and finish methods within.

Here's a sample batch class that runs through all of an org's Contacts and checks a box called myCheckbox__c, if it isn't already checked.

Then, to keep things tidy, I would create a 2nd class with the schedulable interface and a simple method.

Here's that schedulable class:

Then you could queue up the batch class by executing something like this:

Your job will be scheduled, on the hour, every hour.


You could have also implemented both the batchable and schedulable interfaces in the same class and provided a method to do your scheduling.

The new system.scheduleBatch() method that was included in Summer '13

You don't need to:
  1. Implement the schedulable interface (in the same or separate class)
  2. Create a Cron Schedule String (the '0 0 * * * ? *' string above) 
  3. Clean up finished jobs (scheduled jobs hang around until they are manually deleted or system.abortjob() takes care of them.  ScheduledApex clean up after themselves and are removed after running.
The above can be condensed into this:


And scheduled by calling:




Within the system.scheduleBatch() method 3 (and an optional 4th) parameters are provided:
  1. Instance of the batchable class
  2. The Job's name
  3. # of minutes to start the job in
  4. Scope size - 200 is the default for a batchable class' execute method.  This allows you to specify up to 2000 records per batch - just beware of hitting additional limits if you do.