Tuesday, October 23, 2012

How to schedule an apex schedulable class to run after every 10 or 15 minutes

There are scenario in which we need to schedule apex class to run after every 10 minutes or 15 minutes. In order to achieve this requirement, we can create 2 apex scheduler classes. Whenever first scheduler will run, it will perform processing or operation and after that it will schedule second apex schedule class to run after specified interval (in below example, we have mentioned 10 minutes). When second scheduler will run it perform operation or processing and will schedule first apex schedule class to run after specified interval.

First apex scheduler class:

global class Scheduler01 implements Schedulable {
    global void execute(SchedulableContext SC)     
    {
        //Call other class method which will perform operations as it is 
        //recommended that all processing take place in a separate class
        doScheduling();
    }
    public void doScheduling(){
       try{
            dateTime dt=System.now().addMinutes(10); //you can specify 10 mins or 15     
                                                                              //mins or any interval
            String Csec,Cmin,Chr,Cday,Cmonth,CYear;
            Csec=String.valueof(dt.second());
            Cmin=String.valueof(dt.minute());
            Chr=String.valueof(dt.hour());
            Cday=String.valueof(dt.day());
            Cmonth=String.valueof(dt.month());
            CYear=String.valueof(dt.Year());
            String SchTimer=Csec+' '+Cmin+' '+Chr+' '+Cday+' '+Cmonth+' ? '+CYear;
            system.debug('*************SchTimer:'+SchTimer);
            Scheduler02 cas = new Scheduler02();
            system.schedule('Scheduler02: Running at '+System.now().format(), SchTimer, cas);
            //we will delete completed apex scheduled jobs for which state is DELETED

            for( CronTrigger c:[Select State,Id,EndTime,CronExpression From CronTrigger where  

                                        NextFireTime= null  AND State='DELETED' Limit 100]){
                    System.abortJob(c.id);
            }
        }
        catch(exception e){
        }
   }
}

Second apex Scheduler Class:


global class Scheduler02 implements Schedulable {

    global void execute(SchedulableContext SC){
        //Call other class method which will perform operations as it is 
        //recommended that all processing take place in a separate class
        doScheduling();
    }
    public void doScheduling(){
      try{
            dateTime dt=System.now().addMinutes(10);
            String Csec,Cmin,Chr,Cday,Cmonth,CYear;
            Csec=String.valueof(dt.second());
            Cmin=String.valueof(dt.minute());
            Chr=String.valueof(dt.hour());
            Cday=String.valueof(dt.day());
            Cmonth=String.valueof(dt.month());
            CYear=String.valueof(dt.Year());
            String SchTimer=Csec+' '+Cmin+' '+Chr+' '+Cday+' '+Cmonth+' ? '+CYear;
            system.debug('*************SchTimer:'+SchTimer);
            Scheduler01 cas = new Scheduler01();
            system.schedule('Scheduler01: Running at '+System.now().format(), SchTimer, cas);
            //we will delete completed apex scheduled jobs for which state is DELETED
            for( CronTrigger c:[Select State,Id,EndTime,CronExpression From CronTrigger  
                                where NextFireTime=null  AND State='DELETED' Limit 100]){
                    System.abortJob(c.id);
            }
        }
        catch(exception e){
        }
    }
}

9 comments:

  1. these classes show error when trying to save as one is related to other ...
    I am not able to save either of them

    ReplyDelete
    Replies
    1. Just comment below line from Scheduler01 apex classes and save it.
      Scheduler02 cas = new Scheduler02();
      system.schedule('Scheduler02: Running at '+System.now().format(), SchTimer, cas);

      After saving Scheduler01 you can save Scheduler02 class and then uncomment the above mentioned lines from Scheduler01 class and save it.

      Delete
    2. Thank you sir. Good Blog. Please write more blogs about salesforce functionality.

      Delete
  2. Thank you for a clear example on scheduling

    ReplyDelete
  3. hello sir how to use and when we use please give steps how to execute this class please give naviagations please

    ReplyDelete
  4. Hi Sir,
    My requirement is Schedule a batch class from visualforce dynamically like salesforce schedule apex UI thats way i am asking.Ui I created Like below


    Title812180170
    please help me sir


    one frequency picklist field.I this picklist field values are Weekly,Monthly by day,Monthly by date and custom.When i select Weekly picklist value page rendered as Sunday,Monday.......Saturday checkboxes will be displayed.When i select Monthly by day picklist value page rendered as two picklists one is 1st,2nd,3rd,4th and last ,second picklist as Sunday,Monday.......Saturday will be displayed.When i select Monthly by date picklist value page rendered as picklist as 1st,2nd,3rd,4th........31st and last will be displayed.When i select Custom value in picklist page rendered as DayOfMonth(Textbox),Month:(Textbox),DayOfWeek:(Textbox),Year:(Textbox) .I gave Job name ,Startdate,Enddate and PreferredStartTime field as Hours(12AM,1AM....11PM),Minuts(00,01,02....59) and seconds(00,01,02....59).

    NOTE:UI I designed how to perform backend operation based on my UI.

    How to add Frequency as CRON Expresson Dynamically From visualforce page?

    please help me..............

    ReplyDelete
  5. Hi!
    Our company has a cool solution for problems like yours!
    Try this https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000DqCmYUAV. It allows you to execute your schedule at a specified frequency, even every 5 minutes.

    ReplyDelete