Schedulable classes

As a companion to batchable interface, the Salesforce platform provides a schedulable interface. Schedulable classes are considered as asynchronous Apex, because the platform merely adds the job to the queue at the scheduled time. It does not promise that the job will actually run at the scheduled time, but it does promises that it will be queued at that time. The actual processing may take place nearly instantaneously, or at some point in the relatively near future, depending on system resource availability. Using the schedulable interface allows you to queue code at specific times or periodic intervals. This can be implemented either through the web user interface, or through apex code. Like the batchable interface, to utilize the schedulable functionality, you must implement the schedulable interface by implementing the execute()method. The execute() method must accept a single variable of the SchedulableContext type. Like it's Batchable cousin, SchedulableContext is dependency injected by the system. Here is the definition of a simple schedulable class that invokes a batch job:

global class SchedulableClass implements Schedulable {
  global void execute(SchedulableContext SC) {
    // do stuff here.
  }   
}

One of the benefits of the schedulable class interface is that you can use it to trigger batch jobs. Schedulable classes in conjunction with batch jobs enable you to run code at a specific time, while still iterating over massive amounts of data and making callouts as necessary. However, executing batch jobs is not its only feature. By itself, the scheduler can trigger specific code from any class, including itself, to run. However, using the schedulable class to invoke a batch job frees you from certain governor limits. Specifically, schedulable classes do not allow you to make callouts and are limited by standard DML and SOQL limits. However, when you use a schedulable class to queue a batch job, that batch job can make callouts, if it implements Database.AllowsCallouts. Likewise, calling a batch job, also let's you manipulate massive data sets. For instance, if you need to run the opportunity batch job, which we spoke of earlier, on a daily basis, you can use a schedulable class to call the opportunity batch job every day at 2am

Monitoring

The Salesforce platform provides a monitoring system for the Schedulable system. Within your execute method, you can call the getTriggerId() method on the SchedulableContext object passed into it. That method returns an IDId that you can use in conjunction with SOQL to query the CronTrigger object. Using SOQL and the getTriggerId() method, you can get the number of times this schedulable method has fired and the next time it is scheduled to fire. Additionally, you can navigate in the setup menu to monitor | jobs | scheduled jobs to view all the scheduled jobs!

Scheduling from Apex

To set the schedule of a class that implements schedulable from Apex, you use the System.schedule() method. The System.Schedule() method takes three arguments: a String containing the name of the job, a cron expression, and an instance of the schedulable class. Cron expressions are easily the hardest part of this scheduling. Cron expressions take the form of a string representing the time and date that the class should execute at in a seconds, minutes, hours format as well as the day of the month, month, day of the week and, optionally, the year. To complicate matters, cron expressions can include intervals, sets, keywords, and wildcards. The following are a few example cron expressions along with a plain English translation of what they represent.

This expression fires every hour on the hour, for all days, months, and years: 0 seconds, 0 minutes, of every hour, every day of the month, every month, no-set day of the week, with no optional year:

String EXAMPLE_CRON_EXPRESSION = '0 0 * * * ?';

Every hour, 10 minutes after the hour on all days in 2016: or 0 seconds into the 10th minute of every hour every day of the month, with no specific day of the week set, during 2015:

String EXAMPLE_CRON_EXPRESSION = '0 10 * * * ? 2016';

Runs Monday—Friday at 10am or: 0 seconds and 0 minutes into the 10 o'clock hour for unspecified days of the month, during all months for the range of days that are Monday-Friday:

String EXAMPLE_CRON_EXPRESSION = '0 0 10 ? * MON-FRI';

Runs on the last Friday of the month at 10pm, or 0 seconds, and 0 minutes of the 22nd hour on unspecified days of the week, for all months on the L (last) 6th day, that is: Friday:

String EXAMPLE_CRON_EXPRESSION = '0 0 22 ? * 6L';

Runs on the last weekday of each quarter at 10:40pm or: 0 seconds after the 40th minute of the 22nd hour on unspecified days of the month every 4 months starting with month 12 (December):

String EXAMPLE_CRON_EXPRESSION = '0 40 22 ? 12/4 6LW';

As you can tell, cron expressions can range from as simple as running code every hour on the hour to complex expressions that run on the last day of a given fiscal quarter. Once you have created your cron expression, you can schedule the job using the developer console's execute anonymous window, as follows:

Scheduling from Apex

Note that the first argument to System.schedule is what will be displayed as the Job Name field on the Scheduled Job page. This page, found under Setup | Monitor | Jobs | Scheduled Jobs, allows you to cancel jobs that are scheduled as well as see how often jobs have run, and when each job will next run.

Testing schedulable classes

Testing schedulable classes generally follows this pattern. Create a cron expression specifically for testing with a fixed year far in the future, schedule the class with that cron expression, and finally make assertions against the number of times the job has run and the next scheduled time. Effectively this looks as follows:

@isTest
private class CustomScheduledClass_Test {
  
  @isTest static void test_withCronExpressionForOneYearInFuture() {
    Integer oneYearInFuture = Date.today().addYears(1).year();
    String TESTING_CRON_EXPRESSION = '0 0 0 15 3 ? ' + oneYearInFuture;

    Test.startTest();
    String JobIdentifier = System.Schedule('The Best Job Ever', TESTING_CRON_EXPRESSION, new CustomBatchableClass());

    CronTrigger CronTriggerObj = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
                                  FROM CronTrigger 
                                  WHERE id = :JobIdentifier];

    System.assertEquals(CRON_EXP, CronTriggerObj.CronExpression);
    System.assertEquals(0, CronTriggerObj.TimesTriggered);
    System.assertEquals('2022-03-15 00:00:00', String.valueOf(CronTriggerObj.NextFireTime));
    Test.startTest();
  }
}

This pattern is predicated on a simple premise—that your schedulable class merely executes code from another class that is independently tested. This is the recommended path, if for no other reason than it separates the concerns of scheduling from business logic and facilitates rapid, efficient testing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.234.150