Schedule Jobs Using the Apex Scheduler in Salesforce

While working as a Salesforce developer, I was tasked with scheduling the weekly email for sales representatives. To do this, I used the Salesforce Apex Scheduler to schedule a job that runs weekly, retrieves the necessary data, and sends emails to sales representatives.

In this Salesforce tutorial, I will explain the Salesforce Apex Scheduler and how to schedule jobs by creating Apex classes in the Apex scheduler.

Additionally, we will also learn how to delete and abort scheduled Apex jobs.

What is Apex Scheduler?

In Salesforce, Apex Scheduler is a feature that executes Apex classes at specified times. This feature allows us to perform routine operations like data cleanup, batch processing, and other critical tasks regularly without manual intervention.

To invoke Apex classes to run at specific times, we first implement the Schedulable interface for the class and then specify the schedule using either the Schedule Apex page in the Salesforce user interface or the System.schedule method.

Schedule Jobs using Apex Scheduler in Salesforce

In Salesforce, scheduling jobs using the Apex Scheduler involves the following steps.

  • Develop an Apex Class
  • Schedule the jobs using the Apex Class
  • View and Manage Scheduled Jobs

Develop the Apex Class for the Scheduled Job

To create or develop an Apex class, open the Salesforce developer console and select File > New > Apex Class.

Enter the name for the Apex class and click OK. After this, enter the code below in the Apex class.

global class WeeklySalesSummaryEmail implements Schedulable {
    global void execute(SchedulableContext ctx) {
       
        List<Opportunity> closedOpportunities = [SELECT Name, Amount FROM Opportunity 
                                                 WHERE CloseDate = LAST_WEEK 
                                                 AND StageName = 'Closed Won'];
        
   
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] { 'andrew@email.com' });
        email.setSubject('Weekly Sales Summary');
        
        String emailBody = 'Weekly Sales Report:\n';
        for (Opportunity opp : closedOpportunities) {
            emailBody += opp.Name + ' - Amount: ' + opp.Amount + '\n';
        }
        email.setPlainTextBody(emailBody);
        
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        
        System.debug('WeeklySalesSummaryEmail ran at: ' + DateTime.now());
    }
}

Break down the above global apex class code.

  • The class “WeeklySalesSummaryEmail” is marked as global to make it accessible outside the class (for scheduling purposes). Then, “implements Schedulable” shows that this class will implement the Schedulable interface, which is required for scheduling a job.
  • The execute method “SchedulableContext ctx” is called when the scheduled job runs. It contains the logic that needs to be executed at the scheduled time.
  • According to the scenario, the SOQL query will retrieve the list of opportunities closed and won last week, which will be included in the report.
  • Then, there is a logic to create and send an email message.
  • At last, “system.debug” will log the current time the job runs, which can be checked in the Debug Logs.

After entering the code logic of the Apex Class, save it.

Schedule the Jobs using the Apex Class

The following two methods are used to schedule the job in Salesforce.

(a) Schedule Jobs through the User Interface

To schedule the Apex Class, navigate to Salesforce’s setup page and follow the steps below.

  1. Go to the Quick Find box and search, then select Apex Classes. In the Apex Classes setup, click on the button Schedule Apex.
Scheduled jobs using Schedule builder in Salesforce
  1. In the next window, enter the scheduled Job Name and the name of the apex class we created for the scheduled job.

In the field Schedule Using, select the option Schedule Builder.

Apex scheduler in Salesforce
  1. In the section Schedule Apex Execution, select the frequency of the scheduled job ( weekly or monthly). After this, select the Start Date, End Date, and Preferred Start time for the scheduled job.

At last, click the Save button.

Schedule jobs via Apex Class in Salesforce

(b) Schedule jobs programmatically

To schedule a job programmatically, we can use the System.schedule method. This scheduling method needs three parameters: a job name, a CRON expression to match the requirement when the job should run, and an instance of your class.

To schedule the jobs programmatically, open the Salesforce developer console and execute the code in the Apex anonymous window.

String cronExp = '0 0 9 ? * MON *'; 
WeeklySalesSummaryEmail job = new WeeklySalesSummaryEmail();
System.schedule('Weekly Sales Summary Job', cronExp, job);

In the execution code, we used the CRON expression (cronExp), a unique string that decides when to run the job. For example, 0 0 9 means run at 9:00 AM, and “ ? * MON * ” means run every Monday.

Then, the expression “ new (class name) ” will create a new class instance. At last, the System.schedule method will schedule the job using the cron expression.

View and Manage Scheduled Jobs

To view and manage the scheduled jobs, navigate to the Salesforce setup page and search, then select scheduled jobs in the Quick Find box.

In the setup of scheduled jobs, we can view the jobs we scheduled using the Apex scheduler.

We can manage, delete, and pause the scheduled job using the Action buttons.

How To Schedule Jobs Using the Apex Scheduler in Salesforce

This way, we can Schedule Jobs Using the Apex Scheduler in Salesforce by following the above steps.

Delete Apex Schedule Jobs in Salesforce

When it comes to deleting scheduled Apex jobs in Salesforce, you need to know that the scheduled job can not be deleted from Apex code (programatically); however, it can be aborted, which means we can cancel further processing.

Another way to which we can delete the scheduled Apex jobs is from the Scheduled Jobs setup in the user interface.

To delete Apex scheduled jobs, navigate to the Setup> Scheduled Jobs section. Here, you will see the “Delete” and “Pause” job buttons. With the Pause Job button action, the apex job will be cancelled. By pausing the Apex job, you can resume it anytime in the future.

With the delete button “Del”, we can easily delete a scheduled Apex job.

Delete Apex Job in Salesforce

Abort the scheduled job programmatically:

To abort or pause the scheduled job using Apex programming, navigate to the Salesforce Developer Console and open an anonymous Apex window using “Ctrl+E”.

Now, enter the code below in the Apex anonymous window, and execute it to abort the scheduled Apex class. Here, replace the “jobName” with your scheduled Apex job.

String jobName = 'Weekly Opportunity Email';

List<CronTrigger> scheduledJobs = [SELECT Id, CronJobDetail.Name FROM CronTrigger WHERE CronJobDetail.Name = :jobName LIMIT 1];
if (!scheduledJobs.isEmpty()) {
    System.abortJob(scheduledJobs[0].Id);
    System.debug('Scheduled job aborted successfully.');
} else {
        System.debug('No matching job found.');
    }
}

Now, the anonymous code will run, and according to the SOQL query, it will find the scheduled job with the entered ‘job name‘. If it finds the scheduled apex job that matches the job name, then it aborts it using System.abortJob().

If you are running an abort operation for a list of Apex scheduled jobs, then set the limit to 200. If you want to abort more than 200 scheduled Apex jobs, you must rerun the code because the SOQL query limits the list to 200 jobs.

To demonstrate the proof, I have included the debug log, which displays the success message after aborting the scheduled Apex class.

Output:

Abort Scheduled Apex job in Salesforce

To check the status of the Apex job, whether it is queued or aborted, run the following SOQL query in the query editor.

SELECT ApexClassId, ApexClass.Name, Id,JobType, Status FROM AsyncApexJob 

Output:

Howt to abort Apex Scheduled job in Salesforce

In the output of the SOQL query, we can see that the status of the scheduled Apex jobs is marked as Aborted.

This way, we can delete, pause, and abort the scheduled job in Salesforce Apex.

Conclusion

In this Salesforce tutorial, we learned about the Apex scheduler in Salesforce. Then, we discussed the method for creating scheduled jobs using the Salesforce Apex scheduler, in which we developed an Apex class for the scheduled job. Then, using that Apex class, we scheduled the jobs of sending emails using the code and UI methods.

After successfully creating the jobs through the Salesforce Apex scheduler, we also viewed the jobs in the Scheduled jobs section, where we can manage them.

At last, we learned how to delete, pause, and abort scheduled Apex jobs from the Scheduled Jobs setup, as well as using Apex code.

You may also like to read.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.