What is Apex Scheduler

Salesforce schedules (delay execution)  the Apex class for execution at the specified time to run using Apex Scheduler. To take an advantage of Apex Scheduler, first we must write Apex class with Schedulable interface.

Apex Scheduler invokes the Apex class to run at specific time. Anybody who want to schedule the schedule their class, they must have to implement schedulable interface.

What is Schedulable Interface

The class the implements this interface can be scheduled to run at different intervals. This Scheduled interface has several methods they are

public void execute(SchedulableContext SC)

Example

public class MySchedule implements schedule {
	public void execute(ScheduableContext SC) {
		Account a =new Account(Name='Prasanth');
		insert a;
	}
}

Apex Scheduler will run in systemcontext, which means all the classes are executed whether the user has permission or not. We can monitor and stop the execution of Apex scheduler job using Salesforce user Interface from setup.

  • Navigate to Setup | Apex Class | Click Schedule Apex.
  • Enter Job name and select Apex class from the lookup.
  • Select Weekly or Monthly for the frequency and set the frequency desired.
  • Select the start and end dates, and a preferred start time.
  • Click Save.

Apex Scheduler SystemSchedule method

When we implement Schedulable interface, we must use System.Schedulable method to execute the class. System.Schedule() takes 3 parameters they are

  1. Name of the scheduled job.
  2. Expression that is used to represent time and date of the operation.
  3. The object of the class which you want to execute.
***Seconds*** Minutes Hours Day_of_month Month Day_of_week Optional_year

Example :- Write an expression to schedule an operation to 8th September at 12:30 PM. The schedule expression will be as follows

'0 30 12 10 9'

As shown above, the expression is written in the form of “Seconds, minutes, hours, day of month, month, day of the week, optional year”.

Seconds minutes Hours Day-Month Month Day-Week Optional Year
0 30 12 10 9 0 2017

How to implement Apex Scheduler

To implement Apex Scheduler follow the steps given below.

  1. Create an object for the class which has implemented the schedulable interface.
  2. Create the time frame.
  3. Invoke the System.Schedule method with job name, schedule object and time frame.

Schedulable Apex Limitations.

  • We can schedule only 100 jobs at a time.
  • Maximum number of Apex schedule jobs in 24 hours is 2,50,000.
  • Synchronous Web service callouts are not supported in schedulable Apex.