Table of Contents
Introduction
Scheduling is used to execute the Apex code in the background at specific times
Steps To Create A Schedulable Batch Apex Class
We have three steps to create a Schedulable Batch Apex Class.
- First, we need to write a Batch Class that we want to schedule
- After this, write a schedulable batch apex class that contains the code to execute the Batch Class
- In the end, we need to schedule the scheduled apex class either from the Developer Console or from the Apex Scheduler User Interface (UI)
Write A Batch Class
A class that implements Database.Batchable interface is a Batch Class. This Interface includes 3 methods to which the implementing class needs to give a body. The first is the start method which collects the records on which processing needs to be done by Batch Apex and returns a Database.QueryLocator. Then, we have execute method, which does processing on records and returns void. The last method is finish which also returns void and is called post-batch processing
Example:
Write a Batch Class to Update the Status of the Campaign to Completed if it is not Completed.
public class BatchClassCampComplStatus implements Database.batchable { //collects the record using the query public Database.QueryLocator start(Database.BatchableContext bc){ String query = 'SELECT Id, Name, Status, EndDate FROM Campaign WHERE Status != \'Completed\''; return Database.getQueryLocator(query); } //processing of records takes place in execute method public void execute(Database.BatchableContext bc, List camp){ List campList = new List(); for(Campaign cc : camp){ if(cc.Status != 'Completed'){ cc.Status = 'Completed'; campList.add(cc); } } update campList; } //post batch processing code // called at the end public void finish(Database.BatchableContext bc){ System.debug('Batch Job Completed Successfully.'); } }
Write A Schedulable Batch Apex Class
Scheduling is mainly done for data clean-up or weekly maintenance tasks.
A class needs to implement a Schedulable interface and give the body to execute a method that returns void.
Example:
public class SchedulableClass implements Schedulable { public void execute(SchedulableContext ctx){ BatchClassCampComplStatus bccs = new BatchClassCampComplStatus(); Id batchId = Database.executeBatch(bccs, 200); } }
Scheduling the Schedulable Batch Apex Class
There are two ways in which classes can be scheduled. One way is Apex Scheduler UI.
Path: Setup -> Apex Classes -> Click Schedule Apex Button
Another way is using cron expression in the developer console
CRON Expression
SchedulableClass sc = new SchedulableClass();
String cronExp = ‘0 0 8 * * ?’;
System.schedule(‘ScheduleBatchDemo’, cronExp, sc);
0 Comments