How to create and test a Salesforce Schedulable Class

In this post we will see how to create and test a schedulable class. We will use schedulable interface to create a schedulable class and Test.StartTest() and Test.StopTest() methods to write the test class.

Schedulable class can be used for variety of purposes. You can use the class to send regular SMS/Emails. You can use the class to perform some computations at the end of FY.

A schedulable class can be used to run an apex class at fixed times. To write a schedulable class we need to implement the Schedulable interface in our class.

The basic structure of a schedulable class is as below:

global class schexample implements Schedulable{
   global void execute(System.SchedulableContext SC) {
   testclass obj1=new testclass();
      obj1.checkFunc();
   }
   }

In this class I am calling checkFunc method from testclass Apex class. Now that you have created a schedulable class, easiest way to schedule the class is through UI. To that, follow the below steps:

  1. Go to Apex classes in setup, click on Schedule Apex.
How to create and test a Salesforce Schedulable Class

2. Give a Job Name and select your Apex class. Only the classes which have implemented schedulable interface will be shown in the list.

3. Next select the frequency, start date, end date and preferred start time.

4. Click Save.

Track your Scheduled Jobs

You can now track your scheduled jobs in setup. Just search for jobs in setup.

Click on Scheduled Jobs under Jobs. You will see all the jobs that have been scheduled by the users in your org.

Next click on Apex Jobs under Jobs. You will be able to see status of the scheduled jobs which are in progress or aborted due to any error.

How to test a schedulable Apex class

We have written the above class, but what good it is if we can not deploy it to our production org. So now we need to write test classes for our schedulable class.

Following is the test class for above schedulable class:

@istest
class testschexample{
 static testmethod void testFunc() {
  Test.StartTest();
   
schexample sh1 = new schexample();
        String sch = '0 0 23 * * ?';
        system.schedule('Test schexample', sch, sh1);
Test.stopTest();
   
}
 }

We use the Test.StartTest() and Test.stopTest() here to ensure processing finishes before continuing our test.

That’s it. You can now schedule any Apex class using a schedulable class.

You might also like to read: https://initaura.com/delete-class-from-salesforce-production-without-using-eclipse/

Leave a Reply

Your email address will not be published.

Scroll to top