Mastering the Art of Scheduling  Batch Class in Apex

Mastering the Art of Scheduling Batch Class in Apex

Last Updated on June 19, 2023 by Rakesh Gupta

Big Idea or Enduring Question:

  • How can the System.schedule() method be utilized for scheduling an Apex Batch job?

Objectives:

After reading this blog, you’ll be able to:

  • Setup scheduled job though the Salesforce setup
  • Understand the function and significance of the System.schedule() method.
  • Learn step-by-step how to schedule an Apex Batch job using the System.schedule() method.
  • Explore practical examples and use-cases where the System.schedule() method can be implemented.
  • and much more

👉 In the past I’ve written a few articles on Apex. Why not check them out while you are at it?!

  1. Calculate Overall Code coverage in Salesforce
  2. Check if a String is Null, Empty or Blank in Apex
  3. Set Created Date For Test Class sObject in Apex

Business Use case

Isabella Stewart is working as a Salesforce Administrator at Gurukul On Cloud (GoC). Although she is relatively new to Apex programming, she is eager to explore different methods for scheduling batch classes in Salesforce and expand her knowledge in this area.

What is a Scheduled Job?

In Salesforce, a Scheduled Job refers to a feature that allows administrators and developers to schedule the automatic execution of Batch classes at specified times or intervals.

Scheduled Jobs in Salesforce are typically used to perform various actions, such as data updates, record processing, sending email notifications, generating pdfs, and integrating with external systems. They can be particularly useful for tasks that need to be performed at regular intervals, such as hourly, daily, weekly, or monthly.

👉 To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.

global class ScheduleAccountSync implements Schedulable {
   global void execute(SchedulableContext SC) {
      AccounSync ASync = new AccounSync(); 
   }
}

Automation Champion Approach (I-do):

To create a Scheduled Job in Salesforce, you can use the Apex Scheduler through Salesforce setup or System.schedule method from the Developer Console (Execute Anonymous).

 Schedule Jobs Using the Apex Scheduler

Salesforce Apex Scheduler is a feature of the Salesforce platform that allows you to schedule the execution of Apex classes that implements the Schedulable interface at specified times, such as daily, weekly, or monthly.
To schedule a class using Apex Scheduler, follow the steps outlined below:
  1. Click Setup.
  2. In the Quick Find box, type Apex Classes.
  3. Select Apex Classes then click on the Schedule Apex.
  4. Enter the following information:
    1. Name: Sync Account with SAP
    2. Apex Class: ScheduleAccountSync
    3. Frequency: To set up as a daily job, choose the Weekly option and then select every day of the week.
    4. Start: The date and time when the most recent iteration of the scheduled job started.
    5. End:  The date and time when the job either finished or will finish.
    6. Preferred Start Time: The date and time the job is scheduled to run
  5. Click Save.

👉 You can monitor the progress of the job on the All Scheduled Jobs page.

A key limitation of the Apex Schedulerlies in its inability to run a task every few minutes, every six hours, or on specific days such as the first Monday or the last working day of the month. To address this, we can utilize the System.schedule method via the developer console, which allows for more complex scheduling scenarios.

 Schedule Jobs Using the System.Schedule Method

When a class is implemented with the Schedulable interface, the System.schedule method can be used to execute it. Notably, the scheduler operates at the system level, ensuring all classes are executed regardless of individual user permissions.

The System.schedule method take three parameters: the name of the job, an expression signifying the scheduled time and date for the job execution, and the class name. The structure for cron expression is as follows:

Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year

The following are the values for the expression:

Name Values Special Characters
Seconds 0–59 None
Minutes 0–59 None
Hours 0–23 , – * /
Day_of_month 1–31 , – * ? / L W
Month 1–12 or the following:

  • JAN
  • FEB
  • MAR
  • APR
  • MAY
  • JUN
  • JUL
  • AUG
  • SEP
  • OCT
  • NOV
  • DEC
, – * /
Day_of_week 1–7 or the following:

  • SUN
  • MON
  • TUE
  • WED
  • THU
  • FRI
  • SAT
, – * ? / L #
optional_year null or 1970–2099 , – * /

Read this Salesforce Developer guide to learn more about System.Schedule method. It is not possible to update the scheduled jobs. You need to delete the existing job and then schedule it again.

For example, if you want to run the ScheduledAccountSync Apex Class on an hourly basis, specifically five minutes past each hour, then execute the following statement via the Developer Console’s Execute Anonymous.

System.schedule('AccountSyncJob', '0 5 * * * ?', new ScheduleAccountSync());
//AccountSyncJob = Job Name
//0 5 * * * ? = Cron Expression
//ScheduleAccountSync = Apex Class with Schedulable Interface

You can also use CronMaker is a simple application which helps you to build cron expressions for your scenario.

Here are several examples illustrating how to utilize the cron expression.

Schedule a Job to Execute Every Six Hours from Monday to Friday

To schedule a job to run every six hours from Monday to Friday, run the following cron expression:

System.schedule('AccountSyncJobWeekDayPerSixHour', '0 0 0,6,12,18 ? * MON-FRI', new ScheduleAccountSync());

Schedule a Job to Execute Every Four Hours on a Daily Basis

To schedule a job to run every fours hours on a daily basis, run the following cron expression:

System.schedule('AccountSyncJobEveryFourHour', '0 0 0/4 * * ? *', new ScheduleAccountSync());

Schedule a Job That Execute Every Hour on a Daily Basis

To schedule a job that runs hourly throughout each day, utilize the following cron expression:

System.schedule('AccountSyncJobEveryHour', '0 0 0/1 * * ? *', new ScheduleAccountSync());

Schedule a Job to Execute Every 30 minutes on a Daily Basis

To schedule a job that runs every half hour daily, utilize the following cron expression:

System.schedule('AccountSyncJob0', '0 0 * * * ? *', new ScheduleAccountSync());
System.schedule('AccountSyncJob30', '0 30 * * * ? *', new ScheduleAccountSync());

Schedule a job to Execute once daily at 10:00 PM

To schedule a job that runs once daily at 10:00 PM, utilize the following cron expression:

System.schedule('AccountSyncJobOnceInADay', '0 0 22 * * ?', new ScheduleAccountSync());

Schedule a job to Execute Friday and Saturday at 11:00 PM

To schedule a job that runs Friday and Saturday at 11:00 PM, utilize the following cron expression:

System.schedule('AccountSyncJobFri-Sat', '0 0 23 ? * FRI,SAT *', new ScheduleAccountSync());

Schedule a job to Execute Friday  at 11:00 PM

To schedule a job that runs Friday at 11:00 AM, utilize the following cron expression:

System.schedule('AccountSyncJobFriOnly', '0 0 23 ? * FRI *', new ScheduleAccountSync());

Schedule a job to Execute 1st Day of Every Year at 01:00 AM

To schedule a job that runs 1st day of every year, utilize the following cron expression:

System.schedule('AccountSyncJob-1st Day of Year', '0 0 1 1 1 ? *', new ScheduleAccountSync());

Schedule a job to Execute Last Day of Every Month at 01:00 AM

To schedule a job that runs last day of every month, utilize the following cron expression:

System.schedule('AccountSyncJob-Last day of Month', '0 0 1 L * ? *', new ScheduleAccountSync());

Schedule a job to Execute Last Friday of Every Month at 01:00 AM

To schedule a job that runs last friday of every month, utilize the following cron expression:

System.schedule('AccountSyncJob-Last Friday', '0 0 1 ? * 6L *', new ScheduleAccountSync());

Schedule a job to Execute Every 15th of the Month at 12:01 AM

To schedule a job that runs every 15th of the month, utilize the following cron expression:

System.schedule('AccountSyncJob-Every 15th', '0 1 0 15 * ? *', new ScheduleAccountSync());

Schedule a job to Execute First and Third Sunday of Every Month at 2:00 AM

To schedule a job that runs first and third Sunday of every month, utilize the following cron expression:

System.schedule('AccountSyncJob-1st Sunday', '0 0 2 ? 1/1 SUN#1 *', new ScheduleAccountSync());
System.schedule('AccountSyncJob-3rd Sunday', '0 0 2 ? 1/1 SUN#3 *', new ScheduleAccountSync());

Proof of Concept

Formative Assessment:

I want to hear from you!

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? Feel free to share in the comments below.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.