SEOSEO News

How to Schedule an Apex Batch Class in Salesforce


Hello Trailblazers,

In this blog post, we will learn how to schedule an apex Batch Class in Salesforce.

Acceptance Criteria: Write an Apex batch Class to delete all the Contact records older than 1 year. Schedule the batch to delete records automatically.

If you want to learn how to write a simple batch class, you can go with this link.

Here, in this example, we’ll develop a batch class that will have a schedulable interface, containing the logic for deleting contact records older than 1 year.

There are two ways to schedule an apex batch. The first one is with the help of “CRON Expression” and another one is from “Standard Customization” in org. We’ll learn both ways in a one-by-one manner.

Let’s get started…

Schedulable Batch Apex to Delete Records:

public class DeleteContactsBatch implements Database.Batchable<sObject>, Schedulable  {

    public Database.QueryLocator start(Database.BatchableContext context) {
        // Query all Contact records created in the last 1 year
        **** oneYearAgo = System.today().addMonths(-12); 
                    // OR ****.today().addYears(-1); //Use anyone of them
        String query = 'SELECT Id FROM Contact WHERE CreatedDate >= :oneYearAgo';
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext context, List<Contact> scope) {
        // Delete the Account records in the current batch
        delete scope;
    }

    public void finish(Database.BatchableContext context) {
        // Execute any post-processing logic if needed
    }

    public void execute(SchedulableContext context) {
        // Implement the scheduling logic here
        DeleteContactsBatch batchJob = new DeleteContactsBatch();
        Database.executeBatch(batchJob,200); 
    //Here you can also declare batchSize = 200 at starting & use it here. 
    }
}

Let’s break down the things that we did in the above example:

  1. Start() – The start method returns a Database.QueryLocator that defines the scope of records to be processed. Here, in this example, it queries contacts created more than 1 year ago.
  2. Execute() – The execute method processes each batch of contacts. It takes a list of contacts as input and deletes them.
  3. Finish() – The finish method is optional and can be used for any post-processing logic that you might need after all batches have been processed.
  4. Execute() – The execute method of the Schedulable interface is responsible for scheduling the batch job. It creates an instance of the DeleteContactsBatch class and starts the batch job using executeBatch with a specified batch size. (Here we took batch size as 200)

Note: The default batch size is 200 and the maximum batch size is 2000.

How to Schedule an Apex Batch Class:

1. Using CRON Expression:

// Schedule the job to run every day at 5.30 AM
String cronExpression = '0 00 5 * * ? *';
System.schedule('ContactCleanupBatch', cronExpression, new ContactCleanupBatch());

We scheduled this job for 5.00 am. It will run every day.

If you want to explore more about CRON Expression, then you can go with this link. I’ve explained it in detail.

2. From Standard Customization:

To schedule a batch job from Salesforce UI, follow the below steps…

  1. Go to the Setup.
  2. Enter “Apex Class” and search it in the quick find box. Then, Select it.
  3. Click the “Schedule Apex” as directed in the figure below.
    Img1
  4. Give the Job name there and select the Apex Class which you have to schedule.
  5. Select the scheduling frequency. Here, we want to run this batch daily. So, choose the option ‘Weekly’ and then select every day of the week as shown in the figure below.
  6. Then, select the Start **** as well as the Start Time. The End **** is optional. You can adjust it as long as you want to run the batch.
  7. Click Save.

Img2

 

With this, you’ve scheduled the Apex Batch from Standard Customization or Salesforce User Interface.

 

Conclusion:

In this way, we learned how to schedule an Apex Batch with the help of CRON Expression as well as from Setup/Salesforce User Interface.

 

Stay Tuned !!

References:

  1. Batch Apex in Salesforce
  2. Asynchronous Apex in Salesforce

 

You can also read :

1.An Introduction to Salesforce CPQ
2.Salesforce CPQ and its Key Features
3.Unlocking the Power of AI: Einstein for Developers
4.Revolutionizing Customer Engagement: The Salesforce Einstein Chatbot





Source link

Related Articles

Back to top button
Social media & sharing icons powered by UltimatelySocial
error

Enjoy Our Website? Please share :) Thank you!