Monday 6 February 2017

Schedulable Batch Apex In 3 Easy steps In Salesforce

Schedulable Batch Apex In 3 Easy steps In Salesforce

  • There are three main steps involved in this

1. Write Batch Class
2. Write a Scheduled Apex which execute the above Batch Class
3. Schedule the class from the Developer Console or from UI

So here we go...

Step 1. Write Batch Class

global class BatchApexClassExample implements Database.Batchable<SObject>{

 global Database.QueryLocator start(Database.BatchableContext BC) { 
  String soqlquery = 'SELECT Id, name, phone FROM Account';
  return database.getquerylocator(soqlquery);
 }
 // The batch job executes and operates on one batch of records
 global void execute(Database.BatchableContext BC, List<SObject> scope) { 
   // your logic
   System.debug('In BatchApexClassExample - Execute Method ');
 }
 // The batch job finishes
 global void finish(Database.BatchableContext BC) { 
   System.debug('BatchApexClassExample Batch job completed successfully.');
 }
}

Step 2. Write a Scheduled Apex which execute the above Batch Class

global with sharing class ScheduleBatchApexClassExample implements Schedulable {
 global void execute(SchedulableContext sc) {
  ID BatchId = Database.executeBatch(new BatchApexClassExample(), 200);
 }
}

Step 3. Schedule the class from the Developer Console or from UI
  •  From UI : Go to Setup -> Apex Classes -> Click on Schedule Apex button
  •  From Developer Console, check below 
 Execute a schedulable Apex class with System.schedule method

 System.schedule('ScheduleBatchApexClassExampleScheduler', '0 0 * * * ?', new ScheduleBatchApexClassExample());

Good job, we are done. 

If you want to see your batch job scheduled then 

  • Go to Setup—>Monitor –> Scheduled Jobs

If you want to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through standard Salesforce User interface.


Yes I have solution for it. Small code to do so for every 5 minutes.

No comments:

Post a Comment