Wednesday 28 February 2018

One Universal Schedule Class to Execute All Batch Classes In Salesforce

Are you creating schedule class for each batch class if you need to schedule that?

If yes, stop doing like that and start creating a universal (common scheduler class) like below and use it instead of creating multiple schedules.

Step 1: 
Create a universal scheduler class

  1. public class UniversalScheduler implements Schedulable{
  2.   public Database.Batchable<SObject> batchClassName{get;set;}
  3.   public Integer batchScopeSize{get;set;} {batchScopeSize = 200;}
  4.   public void execute(SchedulableContext sc) {
  5.      Database.executebatch(batchClass, batchSize);
  6.     }
  7. }


Step 2:
Let say, You have two batch classes and you want to schedule, then schedule batch class like below using UniversalScheduler class

Batch Class 1:
  1. AccountBatchProcess accBatch = new AccountBatchProcess(); // Batch Class Name
  2. UniversalScheduler scheduler = new UniversalScheduler();
  3. scheduler.batchClass = accBatch;
  4. scheduler.batchSize = 100;
  5. String sch = '0 45 0/1 1/1 * ? *';
  6. System.schedule('Account Batch Process Scheduler', sch, scheduler);


Batch Class 2:
  1. ContactBatchProcess cntBatch = new ContactBatchProcess(); // Batch Class Name
  2. UniversalScheduler scheduler = new UniversalScheduler();
  3. scheduler.batchClass = cntBatch;
  4. scheduler.batchSize = 500;
  5. String sch = '0 45 0/1 1/1 * ? *';
  6. System.schedule('Contact Batch Process Scheduler', sch, scheduler);



No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...