shubham lashkan
Shubham Lashkan

Follow

Shubham Lashkan

Follow
Scheduled Apex in Salesforce

Scheduled Apex in Salesforce

Scheduled Apex - The What, Why, Where & How.

shubham lashkan's photo
shubham lashkan
ยทFeb 26, 2023ยท

3 min read

Play this article

Table of contents

  • What is Scheduled Apex?
  • Why Scheduled Apex is Important?
  • Scenarios where Scheduled Apex can be used
  • Code Example
  • Conclusion

Scheduled Apex is a powerful feature of the Salesforce platform that allows developers to run code on a specific schedule. This can be useful for automating tasks that need to be run on a regular basis, such as sending out email reminders or updating records. In this article, we will discuss what Scheduled Apex is, why it is important, scenarios where it can be used, and provide an example of how to use it.

What is Scheduled Apex?

Scheduled Apex is a feature in Salesforce that allows developers to schedule a piece of code to run at a specific time. The code can be scheduled to run once or in a recurring interval such as daily, weekly, or monthly. In short, we can schedule an apex class to run asynchronously which means at a later point in time.

Why Scheduled Apex is Important?

Scheduled Apex is important because it allows developers to automate tasks that need to be run on a regular basis. By automating tasks, organizations can ensure that important business processes are always up-to-date without the need for manual intervention.

Scenarios where Scheduled Apex can be used

  1. Sending Email Reminders.

  2. Updating Records.

  3. Running Reports.

  4. Data Cleanup.

  5. Integration with External Systems.

Code Example

Let's say whenever an opportunity which has a close date. We want to send an email to the account owner after the close date is over & stage is not set to Closed Won. To do this, we can create a Scheduled Apex job that runs every day and checks for the close date and stage.

To schedule an Apex class to run at regular intervals, first, we have to write an Apex class that implements a schedulable interface provided by Salesforce.

The Schedulable interface contains execute method that must be implemented.

global class StageReminder implements Schedulable {
    global void execute(SchedulableContext SC) {

        List<Opportunity> opportunities = [SELECT Id, Name, CloseDate, Account.Owner.Email,Account.Owner.Name,StageName 
                                     FROM Opportunity 
                                     WHERE CloseDate < TODAY AND StageName != 'Closed Won'];

        for (Opportunity opp : opportunities) {
            String emailBody = 'Hello ' + opp.Account.Owner.Name + ',\n\n' +
                               'This is a reminder that Opportunity ' + opp.Name + ' stage is not set to Closed Won Yet. ' +
                               'Please change the stage as Closed Date is already over.\n\n' +
                               'Thank you,\nYour Company Name';
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new List<String>{opp.Account.Owner.Email});
            email.setSubject('Stage Reminder: ' + opp.Name);
            email.setPlainTextBody(emailBody);
            Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
        }
    }
}

In this example, we have created a class called "StageReminder" that implements the "Schedulable" interface. The "execute" method is the main method that will be called when the scheduled job runs.

In the "execute" method, we first query for all opportunities whose close date is over and whose stage is not set to closed won. We then loop through each opportunity and send an email reminder to the account owner. The email body includes information about the opportunity and a reminder to change the stage.

To schedule this job to run every day at 5:00 PM, we can use the following code:

String cron = '0 0 17 * * ?;
StageReminder reminder = new StageReminder();
System.schedule('Stage Reminder Job', cron, reminder);

This code sets the cron expression to run the job every day at 5:00 PM. It then creates a new instance of the "StageReminder" class and schedules it to run using the "System.schedule" method.

Conclusion

Scheduled Apex is a powerful feature of the Salesforce platform that allows developers to automate tasks that need to be run on a regular basis.

Please don't forget to like, comment and share and you can also check out my other articles. Also, don't forget to subscribe to my newsletter so you can be notified about new articles.

I am looking to get into technical writing so if you want me to write an article then please connect with me on my Twitter handle here.

Let me also know which topic I should write about next.

Did you find this article valuable?

Support shubham lashkan by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this