To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.
Implementing the Schedulable Interface
To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.
The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, from Setup, enter Scheduled Jobs in the Quick Find box, then select Scheduled Jobs.
The Schedulable interface contains one method that must be implemented, execute.
1 | global void execute(SchedulableContext |
The implemented method must be declared as global or public.
Use this method to instantiate the class you want to schedule.
The following example implements the Schedulable interface for a class called mergeNumbers:
1 | global class scheduledMerge implements Schedulable { |
2 | global void execute(SchedulableContext SC) { |
3 | mergeNumbers M = new mergeNumbers(); |
4 | } |
5 | } |
The following example uses the System.Schedule method to implement the above class.
1 | scheduledMerge m = new scheduledMerge(); |
2 | String sch = '20 30 8 10 2 ?' ; |
3 | String jobID = system.schedule( 'Merge Job' , sch, m); |
You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulableinterface for a batch Apex class called batchable:
1 | global class scheduledBatchable implements Schedulable { |
2 | global void execute(SchedulableContext sc) { |
3 | batchable b = new batchable(); |
4 | database.executebatch(b); |
5 | } |
6 | } |
An easier way to schedule a batch job is to call the System.scheduleBatch method without having to implement theSchedulable interface.
Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext getTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string. You can query CronTrigger to track the progress of the scheduled job.
To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the getTriggerIDmethod.
Tracking the Progress of a Scheduled Job Using Queries
After the Apex job has been scheduled, you can obtain more information about it by running a SOQL query on CronTrigger and retrieving some fields, such as the number of times the job has run, and the date and time when the job is scheduled to run again, as shown in this example.
1 | CronTrigger ct = |
2 | [ SELECT TimesTriggered, NextFireTime |
3 | FROM CronTrigger WHERE Id = :jobID]; |
The previous example assumes you have a jobID variable holding the ID of the job. The System.schedule method returns the job ID. If you’re performing this query inside the execute method of your schedulable class, you can obtain the ID of the current job by calling getTriggerId on the SchedulableContext argument variable. Assuming this variable name is sc, the modified example becomes:
1 | CronTrigger ct = |
2 | [ SELECT TimesTriggered, NextFireTime |
3 | FROM CronTrigger WHERE Id = :sc.getTriggerId()]; |
You can also get the job’s name and the job’s type from the CronJobDetail record associated with the CronTrigger record. To do so, use the CronJobDetail relationship when performing a query on CronTrigger. This example retrieves the most recent CronTrigger record with the job name and type from CronJobDetail.
1 | CronTrigger job = |
2 | [ SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType |
3 | FROM CronTrigger ORDER BY CreatedDate DESC LIMIT 1 ]; |
Alternatively, you can query CronJobDetail directly to get the job’s name and type. This next example gets the job’s name and type for the CronTrigger record queried in the previous example. The corresponding CronJobDetail record ID is obtained by the CronJobDetail.Id expression on the CronTrigger record.
1 | CronJobDetail ctd = |
2 | [ SELECT Id, Name, JobType |
3 | FROM CronJobDetail WHERE Id = :job.CronJobDetail.Id]; |
To obtain the total count of all Apex scheduled jobs, excluding all other scheduled job types, perform the following query. Note the value '7' is specified for the job type, which corresponds to the scheduled Apex job type.
1 | SELECT COUNT() FROM CronTrigger WHERE CronJobDetail.JobType = '7' |
Testing the Apex Scheduler
The following is an example of how to test using the Apex scheduler.
The System.schedule method starts an asynchronous process. This means that when you test scheduled Apex, you must ensure that the scheduled job is finished before testing against the results. Use the Test methods startTest and stopTestaround the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the System.schedule method within the startTest and stopTest methods, the scheduled job executes at the end of your test method for Apex saved using Salesforce API version 25.0 and later, but not in earlier versions.
This is the class to be tested.
01 | global class TestScheduledApexFromTestMethod implements Schedulable { |
02 |
03 | // This test runs a scheduled job at midnight Sept. 3rd. 2022 |
04 |
05 | public static String CRON_EXP = '0 0 0 3 9 ? 2022' ; |
06 | |
07 | global void execute(SchedulableContext ctx) { |
08 | CronTrigger ct = [ SELECT Id, CronExpression, TimesTriggered, NextFireTime |
09 | FROM CronTrigger WHERE Id = :ctx.getTriggerId()]; |
10 |
11 | System .assertEquals(CRON_EXP, ct.CronExpression); |
12 | System .assertEquals( 0 , ct.TimesTriggered); |
13 | System .assertEquals( '2022-09-03 00:00:00' , String .valueOf(ct.NextFireTime)); |
14 |
15 | Account a = [ SELECT Id, Name FROM Account WHERE Name = |
16 | 'testScheduledApexFromTestMethod' ]; |
17 | a.name = 'testScheduledApexFromTestMethodUpdated' ; |
18 | update a; |
19 | } |
20 | } |
The following tests the above class:
01 | @istest |
02 | class TestClass { |
03 |
04 | static testmethod void test() { |
05 | Test.startTest(); |
06 |
07 | Account a = new Account(); |
08 | a.Name = 'testScheduledApexFromTestMethod' ; |
09 | insert a; |
10 |
11 | // Schedule the test job |
12 |
13 | String jobId = System .schedule( 'testBasicScheduledApex' , |
14 | TestScheduledApexFromTestMethod.CRON_EXP, |
15 | new TestScheduledApexFromTestMethod()); |
16 |
17 | // Get the information from the CronTrigger API object |
18 | CronTrigger ct = [ SELECT Id, CronExpression, TimesTriggered, |
19 | NextFireTime |
20 | FROM CronTrigger WHERE id = :jobId]; |
21 |
22 | // Verify the expressions are the same |
23 | System .assertEquals(TestScheduledApexFromTestMethod.CRON_EXP, |
24 | ct.CronExpression); |
25 |
26 | // Verify the job has not run |
27 | System .assertEquals( 0 , ct.TimesTriggered); |
28 |
29 | // Verify the next time the job will run |
30 | System .assertEquals( '2022-09-03 00:00:00' , |
31 | String .valueOf(ct.NextFireTime)); |
32 | System .assertNotEquals( 'testScheduledApexFromTestMethodUpdated' , |
33 | [ SELECT id, name FROM account WHERE id = :a.id].name); |
34 |
35 | Test.stopTest(); |
36 |
37 | System .assertEquals( 'testScheduledApexFromTestMethodUpdated' , |
38 | [ SELECT Id, Name FROM Account WHERE Id = :a.Id].Name); |
39 |
40 | } |
41 | } |
Using the System.Schedule Method
After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. This expression has the following syntax:
1 |
|
The following are the values for the expression:
Name | Values | Special Characters |
---|---|---|
Seconds | 0–59 | None |
Minutes | 0–59 | None |
Hours | 0–23 | None |
Day_of_month | 1–31 | , - * ? / L W |
Month | 1–12 or the following:
| , - * / |
Day_of_week | 1–7 or the following:
| , - * ? / L # |
optional_year | null or 1970–2099 | , - * / |
The special characters are defined as follows:
Special Character | Description |
---|---|
, | Delimits values. For example, use JAN, MAR, APR to specify more than one month. |
- | Specifies a range. For example, use JAN-MAR to specify more than one month. |
* | Specifies all values. For example, if Month is specified as *, the job is scheduled for every month. |
? | Specifies no specific value. This is only available for Day_of_month and Day_of_week, and is generally used when specifying a value for one and not the other. |
/ | Specifies increments. The number before the slash specifies when the intervals will begin, and the number after the slash is the interval amount. For example, if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the month, starting on the first of the month. |
L | Specifies the end of a range (last). This is only available for Day_of_month and Day_of_week. When used with Day of month, L always means the last day of the month, such as January 31, February 29 for leap years, and so on. When used with Day_of_week by itself, it always means 7 or SAT. When used with aDay_of_week value, it means the last of that type of day in the month. For example, if you specify 2L, you are specifying the last Monday of the month. Do not use a range of values with L as the results might be unexpected. |
W | Specifies the nearest weekday (Monday-Friday) of the given day. This is only available for Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the class runs on the 19th. If you specify 1W, and the first is a Saturday, the class does not run in the previous month, but on the third, which is the following Monday. |
# | Specifies the nth day of the month, in the format weekday#day_of_month. This is only available forDay_of_week. The number before the # specifies weekday (SUN-SAT). The number after the # specifies the day of the month. For example, specifying 2#2 means the class runs on the second Monday of every month. |
Expression | Description |
---|---|
0 0 13 * * ? | Class runs every day at 1 PM. |
0 0 22 ? * 6L | Class runs the last Friday of every month at 10 PM. |
0 0 10 ? * MON-FRI | Class runs Monday through Friday at 10 AM. |
0 0 20 * * ? 2010 | Class runs every day at 8 PM during the year 2010. |
In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at 8 AM, on the 13th of February.
1 | proschedule p = new proschedule(); |
2 | String sch = '0 0 8 13 2 ?' ; |
3 | system.schedule( 'One Time Pro' , sch, p); |
Using the System.scheduleBatch Method for Batch Jobs
You can call the System.scheduleBatch method to schedule a batch job to run once at a specified time in the future. This method is available only for batch classes and doesn’t require the implementation of the Schedulable interface. This makes it easy to schedule a batch job for one execution. For more details on how to use the System.scheduleBatchmethod, see Using the System.scheduleBatch Method.
Apex Scheduler Limits
- You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs.
- The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods. To check how many asynchronous Apex executions are available, make a request to the REST API limits resource. See List Organization Limits in the Force.com REST API Developer Guide. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included.
Apex Scheduler Notes and Best Practices
- Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.
- Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the limit. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time.
- Though it's possible to do additional processing in the execute method, we recommend that all processing take place in a separate class.
- Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class. See Using Batch Apex.
- Apex jobs scheduled to run during a Salesforce service maintenance downtime will be scheduled to run after the service comes back up, when system resources become available. If a scheduled Apex job was running when downtime occurred, the job is rolled back and scheduled again after the service comes back up. Note that after major service upgrades, there might be longer delays than usual for starting scheduled Apex jobs because of system usage spikes.
The Apex Scheduler is a powerful tool for managing and automating tasks in your applications. Just as tsoHost offers dependable hosting solutions, ensuring your applications run smoothly and efficiently.
ReplyDelete