Schedule in Apex

Introduction

Around 2 years ago, Salesforce has introduced the possibility to run task on a daily basis through something called Apex Scheduler.

If it's nice, a task, which runs once a day, is also not very useful. What about something which runs... every minute!?

Code

If not officially supported, Salesforce allows somehow managing Schedule in Apex, by creating or deleting them (look at the link above). So I came on creating Schedule from a Schedule without forgetting to delete the current running Schedule (because just 25 schedules can run in parallel)... that might sound complicate, but it's not.

global class oneMinuteSchedule implements Schedulable {
  global void execute(SchedulableContext SC)  {     
    //we cancel the previous schedule. 
    abort(SC.getTriggerId());

    //business logic
    //... your static class here.
    //end of business logic

    //we create our new schedule.
    String hour = String.valueOf(Datetime.now().hour());
    String min = String.valueOf(Datetime.now().minute() + 1);
    String ss = String.valueOf(Datetime.now().second());

    if(Datetime.now().minute() + 1 > 59) {
      min='0';
      hour = String.valueOf(Datetime.now().hour()+1); 
    }

    if(Datetime.now().hour() + 1 > 23) {
      hour = '0'; 
    }

    String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';

    oneMinuteSchedule s = new oneMinuteSchedule();

    //we execute it here. it's a one minute schedule according to the previous definition.
    System.schedule('Job Started At ' + String.valueOf(Datetime.now()), nextFireTime, s);
  } 

  private static void abort(String Id){ 
    try{
      //cancel method.
      System.abortjob(Id);
    }
    catch(exception e) {
    }
  }     
}

I experimented a lot with Schedule, and don't ask me why, but if you don't abort the schedule at the start and don't re-plan the schedule at the very end, you will experience some unexpected failures. You should add your business logic just after the abort. To keep this class clean, call static classes instead of code.

Restrictions, Maintenance

Your business logic must be clean, I mean very clean, without unexpected error! If something provoke an Exception, the schedule won't reschedule itself and most likely, your class will be rescheduled automatically 24 hours later... not cool for a one minute schedule. A solution might be to add try / catch to your code. Also, your schedule won't start automatically. You need to start it by your own, which means most likely through the Anonymous Console.

comments powered by Disqus