Tuesday, November 15, 2016

Run a batch class on repeated schedule

Use Case

When you need to run a batch class on repeated schedule , it is no more required to write a specific ‘Schedule’ class  for each batch class.

Solution

Dynamic Schedule class - By using the principle of polymorphism you could create a universal scheduler instead.

Reusable Code

First of all you’ll need to implement the required interface for scheduled Apex classes as shown below.
global class BatchScheduler implements Schedulable {
 
// …
 
}
Next assign global, class-level variables which will be used to access the parameter values required when executing a batch class. Note that we’re creating a variable called “batchClass” whose type is the interface Database.Batchable. This means that any class that implements this interface can be assigned to this variable, this behavior is called polymorphism.
  global Database.Batchable<SObject> batchClass{get;set;}
  global Integer batchSize{get;set;} {batchSize = 200;}
And finally implement the method required by the Scheduleable interface and use the variables to kick off the execution of a batch class.
  global void execute(SchedulableContext sc) {
   database.executebatch(batchClass, batchSize);
  }
It’s done! You now have a class that can be used to schedule any batch class in your Org. The final code being:
global class BatchScheduler implements Schedulable {
  global Database.Batchable<SObject> batchClass{get;set;}
  global Integer batchSize{get;set;} {batchSize = 200;}
 
  global void execute(SchedulableContext sc) {
   database.executebatch(batchClass, batchSize);
  }
}

In order to use it you would have to initiate the schedule from an anonymous block (Developer Console, Eclipse, Mavensmate etc.). For example I would schedule my batch class using something like this:
// Instantiate the batch class
MyBatch myBatch = new MyBatch();
 
// Instantiate the scheduler
BatchScheduler scheduler = new BatchScheduler();
 
// Assign the batch class to the variable within the scheduler
scheduler.batchClass = myBatch;
 
// Run every day at 1pm
String sch = '0 0 13 * * ?';
 
System.schedule('MyBatch - Everyday at 1pm', sch, scheduler);
 

There may be cases where the universal batch scheduler is not appropriate i.e. special pre-work has to be done in the scheduling class, but in most cases I’ve seen it’ll do the job.

No comments:

Post a Comment