Hot Posts

Schedule Apex in Salesforce

The Apex Scheduler lets you delay execution to run Apex classes at a specified time. To schedule jobs, write an Apex class that implements the Schedulable interface, then schedule it for execution on a specific schedule.

How: Reducing the amount of manual work required in daily tasks. Methods:

1. Updating daily logs through the user interface.

2. Running batch classes either daily or at a specific time.

3. Scheduling emails to be sent at a designated time.

4. Performing daily or weekly maintenance tasks.

Approaches:

1. Utilizing the user interface to streamline daily record-keeping.

2. Automating batch class runs through the system. schedule method.

3. Scheduling emails to be sent automatically at a set time.

4. Implementing regular maintenance tasks to minimise manual effort.

1. Schedulable Apex

To schedule any class or code you need to follow two steps :

1. First implement the Schedulable interface for the class

2. Schedule an instance of the class to run at a specific time using the System.schedule method.

global class SomeClass implements Schedulable {
global void execute(SchedulableContext ctx) {
// awesome code here
} }
  • Implementation
public class schedulableApexDemo implements Schedulable{
public void execute(SchedulableContext ctx) {
List<Account> acs = [SELECT Id, Name From Account where
CreatedDate <= TODAY];
for(Account a : acs)
{
a.type = 'Prospect';
}
update acs;
}
}
  • Schedule a method

After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The System.Schedule method uses the user's timezone for the basis of all schedules.

schedulableApexDemo demoReminder = new schedulableApexDemo ();
// timezone in Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '0 0 0 * ? *'; // run class daily at 12 AM
String jobID = System.schedule('Update Accounts', sch, demoReminder);

2. Schedule a batch class

1. Create a batch class

2. Write a schedulable class and call batch class from it.

3. Schedule it.

  • Creating a batch class
global class batchAccountUpdate implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = 'SELECT Id,Name FROM Contact';
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Contact> lstContact) {
for(Contact a : lstContact) {
a.firstName = a.firstName + '-------';
}
update lstContact;
}

global void finish(Database.BatchableContext BC) {
// you can do batch chaining
}
}
  • Write a schedulable class and call batch class from it

To write a schedulable class you need to implement schedulable interface and implement the execute method as well. So put your logic into execute method.

global class DemoScheduleClass implements Schedulable {
global void execute(SchedulableContext ctx) {
// awesome code here
batchAccountUpdate b =new batchAccountUpdate();
Database.executeBatch(b);
}
}
  • Schedule the class

Now, write a cron expression and call the schedule method. Open the anonymous window and copy the below code:-

DemoScheduleClass obj = new DemoScheduleClass ();
// timezone in Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '0 0 2 * ? *'; // run class daily at 2 AM
String jobID = System.schedule('Update Accounts', sch, obj);

3. Schedule a Queueable Class

This is same as scheduling a batch class the difference is in this case you need to implement the queueable interface.

public class queueableDemo implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name='test',Phone='832323232');
insert a;
}
}

Schedulable class for above class

public class queueableScheduleDemo implements schedulable {
public void execute(SchedulableContext context) {
system.enqueueJob(new queueableDemo());
}
}

Now, As above mentioned write a cron expression and call the schedule method. Open the anonymous window and copy the below code:-

queueableScheduleDemo m = new queueableScheduleDemo();
String sch = '0 0 3 * * ?';
String jobID = system.schedule('Queue', sch, new queueableScheduleDemo());

How to schedule a class to run once at a specific time from apex?

Salesforce provides a built-in feature that allows you to schedule apex classes with certain limitations on frequency control. This can be accessed through the setup menu by navigating to apex classes and clicking on the "Schedule Apex" button. However, this method restricts the execution of apex classes to the beginning of each hour. If you require more precise scheduling for your apex classes, you can utilize custom CRON expressions. These expressions offer a more flexible approach to running scheduled apex classes at specific times.

//This can be any time in future

Datetime nextRun = System.now().addHours(2);

//Generating cron expression for next run time

String year = String.valueOf(nextRun.year());

String day = String.valueOf(nextRun.day());

String hour = String.valueOf(nextRun.hour());

String min = String.valueOf(nextRun.minute());

String sec = String.valueOf(nextRun.second());

String cronExp = sec + ' ' + min + ' ' + hour + ' '+day+' '+nextRun.format('MMM').toUpperCase()+' ? '+year;

//Scheduling at the specified time

TrackerSchedulable trackerJob = new TrackerSchedulable();

System.schedule('Tracker Job', cronExp, trackerJob);

Post a Comment

0 Comments