Salesforce Batch apex - Example, scenarios and scheduling

This batch apex tutorial will help you understand the basic use of batch apex class, scenarios where you can use batch apex and how to schedule it to run automatically.

What is a salesforce batch apex
Batch apex is basically exposed as an interface that has to be implemented. A batch apex job is asynchronous execution of code unlike triggers that are synchronous in execution. 

So Why use batch apex, why don't use trigger itself to build the logic?

Batch apex is basically a way to process large number of records as asynchronously in smaller batches. Say for example you have 5 million records to validate for a certain condition, you wouldn't be able to do that through trigger or a single developer console execution (it would hit governor limits). What batch apex does is, it queries all the records and then start sending smaller batches for execution. And all of these happens asynchronously, that is each smaller batch is considered as separate transaction with governor limits being reset for each of these transactions.

How to build a batch apex and how does it work

Batch apex basically implements a interface provided by salesforce. A batch apex can be run through developer console or can also be scheduled to run using the schedule interface.
A batch apex consists of three methods. One to query all the records for iteration. Second method is used for processing the actual logic and third to do the find action one time after all the processing is completed. Lets see the three batch apex methods in detail.
  1.    Start method
  2.    Execute Method
  3.    Finish Method
Start method is called at the start of the batch Apex. Start method collects all the records using the query.

Execute method is called after the start method, it receives the list of record which can be processed as required.

Finish method is called at last after the batch process is completed. Finish method can be left blank if not required or can be used to send the email confirmations.

Let us write a simple batch apex class and also schedule it.
Requirement: Write a batch apex class to update all the account records daily(update field description on account)


global class UpdateAccountBatch implements Database.Batchable{ 
    String query; 
    global Database.querylocator start(Database.BatchableContext BC){ 
         Query = 'Select id,name,Description from account'; 
          return Database.getQueryLocator(query);
     } 

    global void execute(Database.BatchableContext BC, List scope){ 

        List accList = new List(); 
        for(account s : scope){
              s.Description = 'Updated in batch apex class'; 
               accList.add(s); 
         } 
          update accList; 
     } 

     global void finish(Database.BatchableContext BC){

         //comment - finish method can remain blank
     }
}


The start method queries all the accounts and passes these records in batches of 200 records per batch to execute method in list "Scope" [List<account> scope] where these records are processed(Updated).

Batch apex scenarios in salesforce

Batch apex is a asynchronous way of executing processes that run in the background. Batch apex can be used to process records in smaller chunks rather then all records at once. Lets see a real time scenario of batch apex usage in salesforce.

1. Scenario One

The ask or the requirement: A partner account should be deactivated if any of its contacts fail to log monthly time-sheet within time in salesforce. Consider the time-sheet be filled in a custom object which is child of contact. (This scenario will also demonstrate how to use batch apex to update records in salesforce)

This requirement can be met by implementing a batch apex that queries all the partner accounts in the start method of batch apex. Then use batch apex execute method to update the records (accounts) that is deactivate the account if there are any contacts that haven't submitted the time-sheet for previously month. Consider the batch apex size set at one, the execute method will receive 1 account for each execution. In execute method query contacts or each of the account and check if the time-sheet was submitted or not. If any of the contacts are found to be not complying with the time-sheet i.e if any of the contacts do not have time-sheet record logged for last moth then mark that account for deactivation.

2. Scenario Two

The ask or the requirement : For all the accounts that do not qualify for the business extension  for next month make sure their contacts are invited for a meeting to discuss the next steps. So basically automatically create meeting or the event for all primary contacts of such accounts on every starting of month. This scenario will help in understanding how to use batch apex to insert records.

Solution: Write a batch apex with a satrt method that queries all the accounts that do not qualify the criteria of extensions for next month. The pass each of the account to execute method. Write logic to query each of the contacts of the accounsa nd insert a aciity recird or the event record and set the subject as meeting and all other fields and insert the record.

3. Scenario Three

The requirement or the ask : All the partner accounts that have remained deactivated for more than 6 months should be deleted from the system. This will example scenario will also demo the use of delete records in batch apex.

Solution: Query all the accounts in start method with a where clause that uses the the custom field that store the deactivation date. Where clause will help in querying all such accounts that have deactivation date greater six months. In the execute method simply use delete dml to delete such accounts.

How to schedule a Batch Apex class

Once you have batch apex class, you may either want it to run only once and may be occasional whenever you want. You may also want the batch to run periodically say for example every day once or every hour or every month. Lets see how you can schedule the batch apex and let it run on its own. Next step after writing the batch apex is to write the scheduler class that implements schedulable interface and instantiates your batch apex class. Below is the example of scheduler class for the batch apex class that we wrote above.

global class UpdateAccountBatch_Schedular implements Schedulable{ 
    global void execute(SchedulableContext sc) { 
         UpdateAccountBatch uab = new UpdateAccountBatch (); 
         database.executebatch(uab);
     } 
}


Next thing depends on what frequency you want the batch apex to run. Writing the scheduler class itself will not run the batch, nor it will run on its own. You need set the frequency yourself. This can be done either from the setup and you can schedule batch apex from developer console. With declarative way you can run it weekly basis or monthly basis. And with this way you can run it as max once a day. That is the highest frequency you can have.

Steps for manually scheduling the batch apex, Go to set up -> Apex Classes --> Press button "Schedule Apex"

Select your Apex scheduler class "UpdateAccountBatch_Schedular" in the look up and select the time and frequency as required.

How to schedule batch apex for every day

With a batch apex class and scheduled apex class ready we can use set up to schedule the class to run every day. Like in the below snapshot you can see that the batch apex is scheduled to run every day of every week at 8PM. That is highest frequency of execution you can have using set up.


























But, like we discussed above the requirement could be to run the batch apex every hour or even every 30 minutes. For this kind of frequency we need to run run system.schedule and make use of cron expression for scheduling the batch apex.

Run System.Schedule to schedule the batch Apex

Lets try to build system.schedule with cron expressions for having different frequencies.

How to schedule the batch apex directly from developer console.

You can schedule the batch apex from developer, by running the script only once. For this you need to have the scheduler class ready like the one we have above. You need to run system.schedule from the developer console. Lets see how we build the system.schedule .

System.schedule method has three arguments that we need to set.
  1. Name of the job
  2. Cron expression, this will indicate the date and time when you want the batch apex to run.
  3. New instance of the schedulable class.
An example for the above batch class that we wrote the system.schedule example will be as below,

UpdateAccountBatch_Schedular schuleinsatnce = new UpdateAccountBatch_Schedular();
String cronexpression = ‘0 0 10 * * *’
system.scheule('job-everyday-at-10am',,schuleinsatnce);

Building CRON expressions

Lets try understanding how we use the cron expression to schedule the jobs in salesforce. In the above example we just saw how we can run a script to schedule a job that runs every day at 10 am. For setting the timing we used cron expression, but lets see how exactly to use cron expression to build the exact time, date and frequency as per our needs.

There are basically 7 parameters that can be set in a cron expression. Below are the parameters and their order that we can set, not all are mandatory.

Seconds : 0–59
Minutes :0-59
Hours :0-23
Day_of_month : 1-31
Month : 1-12
Day_of_week : 1-7
optional_year : null or 1970-2099

?: No value
*: All values
L: last

For example if we want to set the frequency to be every day at 3PM, then set seconds to be 0, minutes to 0, hours to 15 (this will set it to 3PM),*,*,*,*

Here last four stars are to indicate every day of month, every month, every day of week and every year. The final statement will be as below,

UpdateAccountBatch_Schedular newins = new UpdateAccountBatch_Schedular();
String cronexpression = ‘0 0 15 * * *’
system.scheule('job-everyday-at-3pm',cronexpression,newins);

We already saw that a batch apex can be scheduled through set up for a maximum frequency of once per day. And for other frequencies more than once per day we need to use system.schdule method with cron expressions. Lets try to build the developer console scripts that can run at different frequencies that we commonly use.

1. schedule batch apex for every hour

To run the batch every hour set hour to * that is every hour, also set month, day of week to *. Set seconds and month to 0 so that it start at 0th minute and second. An example below that will run the batch apex every hour of every day.

String CRONEX = '0 0 * * * ?';
mySheduledBatchableclass schcl = new mySheduledBatchableclass();
system.schedule('every hpur job', CRONEX, schcl);

2. schedule batch apex for every 15 Minutes or 10 Minutes

For scheduling a batch apex for every fifteen minutes you will have to create 4 different entries and it wont happen with a single system.schdule method as above. 4 different method set at equal intervals of 15 minutes minutes like at 0th minute, 15th minute, 30th minute and 45th minute. Be warned that this will create 4 different job entries and will eat into the limits on the jobs that can be scheduled. Thus be careful when doing such things specially if you have a huge org. Lets see the four snippets,

String CROfirst = '0 15 * * * ?';
mySheduledBatchableclass schcl = new mySheduledBatchableclass();
system.schedule('every hpur job', CROfirst, schcl);

String CROSec = '0 30 * * * ?';

mySheduledBatchableclass schcl = new mySheduledBatchableclass();
system.schedule('every hpur job', CROSec, schcl);

String CROthird = '0 45 * * * ?';

mySheduledBatchableclass schcl = new mySheduledBatchableclass();
system.schedule('every hpur job', CROthird, schcl);

String CROfour = '0 0 * * * ?';

mySheduledBatchableclass schcl = new mySheduledBatchableclass();
system.schedule('every hpur job', CROfour, schcl);

Similarly, if you want to schedule batch apex for every 10 Minutes, the entries will be more. That is for 60 minutes there will be 60 divided by 10 equals 6 entries. To schedule batch apex for every 30 minutes the entries will be 2 each at 0th minute and 30th minute.

How to check the scheduled job ?

Go to set up -> Monitoring -> Scheduled Jobs

3 comments:

  1. Hi,
    How to implement above image dynamically from visualforce page?

    help me...........

    ReplyDelete
  2. Nice explanation,, good work!!
    here another great topic about salesforce!! hope you will like it.

    http://www.engineeringway.com/2018/02/set-up-single-sign-on-for-your-internal.html

    ReplyDelete