Learn How to Write Salesforce Schedulable Apex Class and Corresponding Test Class

Posted by Niraj Wani
June 18th, 2018

Salesforce provides different ways of processing asynchronously and it is typically used in scenarios for callouts to external systems, operations that require higher limits, and code that needs to run at a certain time. Processes can be later run in a separate thread, using Asynchronous Apex. It comes in multiple flavors like future methods, batch apex, queueable apex and scheduled apex. This blog explores how to write schedulable apex class and corresponding test class.

Introduction to Schedulable Apex

The apex scheduler provides a medium to run apex classes at specific times. This is an ideal way for scheduling maintenance tasks that needs to be executed on a daily or weekly basis. Apex scheduler can be used to schedule any Apex class that implements Schedulable interface. Schedulable interface makes it mandatory to implement execute method – the only method that this interface contains.

Example of such class –

Basic structure of Apex class with Schedulable interface:

1 global class AccountUpdates implements Schedulable {
2 global void execute (SchedulableContext ctx) {
3 // code
4 }
5 }

Scheduling Apex class

Scheduling Apex class can either be done programmatically or from the Apex Scheduler UI.

Programmatic Scheduling / Using the System.Schedule Method

System.Schedule method allows scheduling Apex class programmatically. Three input parameters are considered in this method: CRON expression for time and date the job schedule, name for the job, and the name of class.

Code to schedule an Apex class programmatically –

1 AccountUpdates acctUpdates = new AccountUpdates();
2 // Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
3 String sch = ’20 30 8 10 2 ?’;
4 String jobID = System.schedule(‘Account Updates’, sch, acctUpdates);

Manual Scheduling via UI

It is also possible to schedule an Apex class from the user interface by executing below steps:

  1. 1. Navigate to Setup, search for Apex in the Quick Find box, then select Apex Classes.
  2. 2. Click Schedule Apex.
  3. 3. Enter the job name, Example – Daily Account Update.
  4. 4. Click the lookup button to search Apex class and select the class.
  5. 5. Select Weekly or Monthly for the frequency and set options as needed.
  6. 6. Select the start and end dates, and also the preferred start time.
  7. 7. Click Save.

Testing Scheduled Apex

For a Scheduled Apex test it is necessary that the scheduled job is finished before testing against the results. To do this, use startTest and stopTest again around the System.schedule method, to ensure that the processing finishes before continuing your test.

Below is the structure of a test class for testing Scheduled Apex. It’s important to note that as soon as stopTest method finishes execution, the job is finished synchronously, to ensure the test results can be validated immediately after stopTest.

@isTest
private class AccountUpdatesTest {

// Dummy CRON expression: midnight on Feb 28.
// Because this is a test, job executes
// immediately after Test.stopTest().
public static String CRON_EXP = ‘0 0 0 28 2 ? 2022’;

static testmethod void testScheduledJob() {
// Create Test Data
Test.startTest();
// Schedule the test job
String jobId = System.schedule(‘Account Updates’’,
CRON_EXP,
new AccountUpdates());
// Key thing to Note: Stopping the test will run the job synchronously
Test.stopTest();
// Now that the scheduled job has executed,
//Use System.assertEquals to confirm test success
}
}

From the myriad items available in Scheduled Apex, you should ensure to bear in mind the following information:

  • At a time, you can have only 100 scheduled Apex jobs. There are maximum number of scheduled Apex executions per a 24-hour period.
  • For scheduling a class from a trigger, you should be extremely cautious. The trigger shouldn’t exceed the limit of adding more scheduled jobs.
  • Only if your scheduled Apex executes a batch job, callouts are supported from the batch class. Scheduled Apex otherwise does not support Synchronous Web service callouts. For making callouts in this case, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex.

About the Author:

Niraj has extensive experience in Enterprise CRM applications, solution design, architecture and system integrations. 3x Salesforce Certified Professional, AWS Certified Cloud Practitioner and playing role of an application architect in his current assignment.

Niraj Wani  

(nirajw@hexaware.com)

 

For more insights please feel free to connect with us on marketing@hexaware.com.

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *