How to Schedule Apex to run every 2, 5, 10 minutes in Salesforce

Hello Folks, In this post, I’m going to show you how you can schedule an apex class every 2  minutes or whatever interval you want to set in minutes using the CRON expression.

Schedule Apex every 2 or n minutes in Salesforce

In Salesforce Apex, Scheduling a class every 2 minutes or n minutes is not possible by the standard Salesforce user interface, But you can achieve this by following the below code.

As you are going to schedule an Apex Class so make sure your class implements the schedulable Interface.

Learn more about Salesforce Flow Bootcamp

In this example, I’m scheduling this apex class from the finish method of a batch you can use the scheduling logic as per your logic or scenario.

By doing this you will get a recurring schedule class that executes your logic every n minutes of your choice.

Get complete Roadmap To Learn Salesforce Admin And Development 👇

Share Now

Shubham is the Founder of Salesforce Geek. He is also a Salesforce Certified Consultant.

Similar Posts

2 thoughts on “How to Schedule Apex to run every 2, 5, 10 minutes in Salesforce

  1. Hi.
    There are 2 issues:
    1.Few syntax error in the code snippet that prevent it from compiling (line 22 – no such contractor, 23- missing CONSTANT)
    2.As it is not setting any expression for the day, then by default it will be daily, therefore in the finish before scheduling the next run you need to abort the previous job. Otherwise after 100 cycle you will have 100 jobs in the scheduled jobs and it will hit the limit.

    I’m using app tool for managing the jobs and recently publish it: https://lc169.blogspot.com/2022/02/tool-for-manage-and-build-and-run.html

  2. I solved this by doing the following:

    copied a piece of code that Schedules as well abort the previous job to avoid hitting governor limits:

    public void finish(Database.BatchableContext BC){
    RescheduleJob();
    }

    public void RescheduleJob(){
    // If job currently scheduled remove it
    List SchJobs = [SELECT Id FROM CronTrigger where CronJobDetail.Name = ‘YOUR_BATCHJOB_NAME’];
    String MyJobID;
    if (SchJobs.size() > 0){
    MyJobID = SchJobs[0].Id;
    // removing the job from the schedule
    System.abortjob(MyJobID);
    }
    // calculating the minute mark which is 5 minutes from now
    DateTime Cdatetime = DateTime.now();
    DateTime NewDateTime;
    NewDateTime = Cdatetime.addMinutes(5);// Reschedule job in 5 minutes from time job finishes
    Integer min = NewDateTime.minute();
    // scheduling job for a certain minute of the hour
    String sch = ‘0 ‘ + string.valueOf(min) + ‘ * * * ? ‘;
    // rescheduling the job
    System.schedule(‘YOUR_BATCHJOB_NAME’, sch, new YOUR_BATCHJOB_NAME());
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *