Schedule apex (Salesforce UI and CRON Expression -Asynchronous Apex)

Ranbir Kumar Das
Salesforce Champion
3 min readNov 18, 2020
Photo by Stas Knop from Pexels

Use the Apex scheduler and the Schedulable interface if you have specific Apex classes that you want to run on a regular basis, or to run a batch Apex job using the Salesforce user interface. Scheduled apex is all about running a piece of apex code at some particular time within a period of time. Schedule apex in Salesforce is a class that runs at a regular interval of time. To schedule an apex class, we need to implement an interface Schedulable.

execute is the mandatory method for Schedulable class as it is an interface

Syntaxpublic class Scheduleclass implements Schedulable{
public void execute(SchedulableContext sc){
//----------- Your Code Here
}
}

For example, if we want to update the name of the account which is created today we will create the schedulable class as below

public class Scheduleclass implements Schedulable{
public void execute(SchedulableContext sc){
List<account> acclst=new List<account>();
List<account> acc=[select id,name from account where createddate=today];
for(Account acc1:acc){
acc1.name=acc1.name+'hello';
acclst.add(acc1);
}
update acclst;
}
}

How to execute the scheduled Class?

We can call schedule class in two way

  1. User interface
  2. Programatically

User-interface

Programatically

It is simple we just have to use the

Syntax
system.schedule('Title',expression,classinitilizaton);
//classinitilizaton: class initilization

the above class can be scheduled like

system.schedule('CRON SET','0 0 12 * * ?',new Scheduleclass());

Title:

It can be anything like the heading.

Cron Expression:

This is very important. expression guide the scheduled class to run at a specific time. It has 7 parameters. below I have explained each and everything.
syntax:
Second Minute Hour Day Month Day_of_the_week Year

So cron expressions can be as simple as this: * * * * ? *

Second: it can be between 0–59
Minute: it can be between 0–59
Hour: It can be 0–23 (Consider Before 12 is AM and after 12 is PM)
Day: 1–31
Month:1–12 or JAN-DEC
Day_of_the_week: 1–7 or SUN-SAT
Year: empty, 1970–2099

Note: in any corn expression Day and Day_of_the_week can not be used simultaneously.

* denotes all and ? denotes none.

0 0 12 * * ? =Fire at 12pm (noon) every day
0 15 10 ? * * =Fire at 10:15am every day
0 15 10 * * ? 2020 =Fire at 10:15am every day during the year 2005

How to monitor the Schedule Class ?

We can monitor the progress from the scheduled job in setup.

--

--

Ranbir Kumar Das
Salesforce Champion

I M Believer, Helper, Chaser, Thinker, Rich, Explorer, Prayer, Boss, Freedom, Fearless, Investor, Faith, Creator, trillionaire, CSM, Salesforce certified