How to create a scheduled task in salesforce?

Frank
2 min readAug 22, 2020

Sometimes you maybe have to implement such a requirement that needs to execute period (e.g. the interest should be calculated at the begin of every month). There is a rational way provided by salesforce to implement this kind of requirements.

1, Firstly, you should extend the class named Schedulable, and override the function named execute like the following code:

global class ScheduledApexInterestAccumulation implements Schedulable {    global void execute(SchedulableContext ctx) {        // put your code here to do periodly the task
}
}

After inputting, submitting, and testing the code, you can put it as a scheduler into the system, which will be called according to the parameter you passed. There are two ways to create a scheduler in salesforce, and the first way is in develop console by manual commands like this:

ScheduledApexInterestAccumulation p = new ScheduledApexInterestAccumulation();
String sch = '0 41 14 21 8 ? 2020';
system.schedule('One Time Pro', sch, p);

The above commands insert a scheduler which runs once at 2020–8–21 14:41:00, the running function is ScheduledApexInterestAccumulation.execute. If you want to run this function the 1st day of every month, only modify as follows:

ScheduledApexInterestAccumulation p = new ScheduledApexInterestAccumulation();
String sch = '0 41 14 1 * ?';
system.schedule('One Time Pro', sch, p);

In this way, you have deployed a scheduler which can run 1st day at 14:41:00 every month. You can query it in salesforce page:

All scheduled Jobs in salesforce

Or using the following commands in the develop console:

// query the next scheduler
SELECT Id, TimesTriggered, NextFireTime
FROM CronTrigger

There is another way to deploy a scheduler in salesforce management page: Setup > Custom Code > Apex Classes, and click the button named ‘Schedule Apex’.

By the way, you can view and cancel the scheduled class in the develop console with the following commands:

List<CronTrigger> JOBIDLIST = new List<CronTrigger>();
JOBIDLIST = [select id from CronTrigger];
for(CronTrigger job:JOBIDLIST )
{
System.abortJob(job.id);
}

--

--

Frank
0 Followers

A C/C++ programmer has a strong curiosity with new technology (e.g. Go, Dart, Apex).