Ora

How do I schedule an apex job from developer console?

Published in Salesforce Apex Scheduling 6 mins read

To schedule an Apex job from the Developer Console, you use the System.schedule() method within the Execute Anonymous window. This method allows you to programmatically set up an Apex class to run at specific intervals as a scheduled job.

How to Schedule an Apex Job from the Developer Console

Scheduling an Apex class as a batch job, or any Apex job that implements the Schedulable interface, directly from the Developer Console is accomplished by executing a System.schedule() statement in the Anonymous window. This method requires a unique job name, a cron expression to define the schedule, and an instance of your schedulable Apex class.

Prerequisites: Your Schedulable Apex Class

Before you can schedule an Apex class, it must implement the Schedulable interface and include the execute method, which contains the logic you want to run.

public class MyScheduledJob implements Schedulable {
    public void execute(SchedulableContext sc) {
        // Your Apex code logic goes here
        // For example, update records, send emails, perform calculations, etc.
        System.debug('MyScheduledJob executed at: ' + System.now());
        List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
        for (Account acc : accounts) {
            System.debug('Account Name: ' + acc.Name);
        }
    }
}

Understanding System.schedule()

The System.schedule() method is the core component for scheduling Apex jobs. Its signature is:

System.schedule(jobName, cronExpression, schedulableClassInstance)

  • jobName: A String that serves as a unique identifier for your scheduled job. This name will appear in the "Scheduled Jobs" list in Salesforce Setup.
  • cronExpression: A String that specifies the recurring schedule for the job. This is a powerful, flexible format that allows precise timing.
  • schedulableClassInstance: An instance of the Apex class that implements the Schedulable interface.

Cron Expression Format

The cronExpression is a critical part of defining your job's schedule. It uses a specific format with six fields representing different time components:

Seconds Minutes Hours Day_of_month Month Day_of_week

Field Accepted Values Description
Seconds 0-59 The second within the minute.
Minutes 0-59 The minute within the hour.
Hours 0-23 The hour of the day (24-hour format).
Day_of_month 1-31 or ? or L or W or LW or # The day of the month. ? means "no specific value" (used when Day_of_week is specified). L means last day of the month. W means nearest weekday. # refers to the Nth day of the week (e.g., 4#2 for the second Thursday).
Month 1-12 or JAN-DEC The month of the year.
Day_of_week 1-7 or SUN-SAT or ? or L or # (1=Sunday) The day of the week. ? means "no specific value" (used when Day_of_month is specified). L means last day of the week in the month (e.g., 5L for the last Friday). # refers to the Nth day of the week (e.g., 6#3 for the third Friday).

Important Notes for Cron Expressions:

  • Use ? for either Day_of_month or Day_of_week when the other is specified. You cannot specify both.
  • All times are in Greenwich Mean Time (GMT). Be mindful of time zone conversions.
  • For more details, refer to the Salesforce documentation on Cron Expressions.

Step-by-Step Guide to Scheduling

Follow these steps to schedule your Apex job using the Developer Console:

  1. Ensure Your Schedulable Class Exists: Make sure you have an Apex class that implements the Schedulable interface and contains the logic you want to execute, as shown in the example above (MyScheduledJob).

  2. Open the Developer Console:

    • In Salesforce, click the Gear icon (Setup) in the top-right corner.
    • Select Developer Console.
  3. Open the Execute Anonymous Window:

    • In the Developer Console, navigate to Debug > Open Execute Anonymous Window.
    • Alternatively, press Ctrl+E (Windows) or Cmd+E (Mac).
  4. Enter the System.schedule() Call:

    • In the Execute Anonymous window, type the System.schedule() statement.
    • Example: To schedule MyScheduledJob to run daily at 2:00 AM GMT:
    String jobName = 'Daily MyScheduledJob';
    String cronExp = '0 0 2 * * ?'; // Run every day at 2:00 AM GMT (Seconds Minutes Hours Day_of_month Month Day_of_week)
    MyScheduledJob myJob = new MyScheduledJob(); // Instantiate your Schedulable class
    System.schedule(jobName, cronExp, myJob);
    System.debug('Job ' + jobName + ' scheduled successfully!');
    • You can also schedule it for a specific date and time, for instance, to run once at 10:30 AM GMT on March 15th, 2025:
      String jobName = 'One-time MyScheduledJob';
      String cronExp = '0 30 10 15 3 ? 2025'; // Run on March 15, 2025, at 10:30 AM GMT
      MyScheduledJob myJob = new MyScheduledJob();
      System.schedule(jobName, cronExp, myJob);
      System.debug('Job ' + jobName + ' scheduled successfully for a specific date!');
  5. Execute the Code:

    • Click the Execute button (or Ctrl+E / Cmd+E).
    • A message will appear indicating successful execution. If you opened the Logs panel, you might see the debug message from your System.debug() call.

Monitoring Scheduled Jobs

After scheduling, you can monitor your job's status and upcoming executions in Salesforce Setup:

  1. Navigate to Setup.
  2. In the Quick Find box, type Apex Jobs (or Scheduled Jobs).
  3. Click Apex Jobs or Scheduled Jobs.

Here you will see a list of all scheduled jobs, including the one you just created. You can monitor its status, next scheduled run, and delete it if needed.

Practical Insights

  • Idempotency: Ensure your schedulable code is idempotent, meaning running it multiple times yields the same result as running it once, especially if there's a chance of accidental double-scheduling or retry.
  • Error Handling: Implement robust error handling within your execute method to manage exceptions gracefully and log issues for debugging.
  • Testing: Always write comprehensive test classes for your Schedulable Apex classes. These tests must cover the execute method and ensure the class can be successfully scheduled.
  • Governor Limits: Be mindful of Salesforce governor limits, especially for CPU time, DML statements, and query rows, as scheduled jobs are subject to these limits.
  • Unscheduling Jobs: To unschedule a job, you can find its CronTrigger record and delete it. For example, using Execute Anonymous:
    List<CronTrigger> jobs = [SELECT Id, CronJobDetail.Name FROM CronTrigger WHERE CronJobDetail.Name = 'Daily MyScheduledJob'];
    if (!jobs.isEmpty()) {
        System.abortJob(jobs[0].Id); // Use System.abortJob() or delete the CronTrigger record
        System.debug('Job ' + jobs[0].CronJobDetail.Name + ' unscheduled.');
    }

By following these steps, you can efficiently schedule your Apex jobs directly from the Developer Console, enabling powerful automation within your Salesforce org.