Wednesday 10 June 2015

How to schedule one class to run in every 1 mins?

Sometimes we need to run a class in every minute to do some operation.


    // This section of code will schedule the next execution 1 minutes from now
   global class Scheduling_Svc_WS_CreateBatch implements Schedulable{

 // Execute method
    global void execute(SchedulableContext SC) {

         datetime nextScheduleTime = system.now().addMinutes(1);
         string minute = string.valueof(nextScheduleTime.minute());
         string second = string.valueof(nextScheduleTime.second ());
         string cronvalue = second+' '+minute+' 0-23 * * ?' ;
         string jobName = 'selfReschedulingClass ' +nextScheduleTime.format('hh:mm');
         Scheduling_Svc_WS_CreateBatch p = new Scheduling_Svc_WS_CreateBatch();
          system.schedule(jobName, cronvalue , p);
         // this section of code will abort the current schedule job
         system.abortJob(sc.getTriggerId());
    }
}
  

1 comment:

Asish Kumar Behera said...

DateTime currentDateTime=System.now().addMinutes(1);
String nextScheduleTime=String.valueof(currentDateTime.second()) +' '+String.valueof(currentDateTime.minute())+' '
+String.valueof(currentDateTime.hour())+' '+String.valueof(currentDateTime.day())+' '
+String.valueof(currentDateTime.month())+' ? '+String.valueof(currentDateTime.Year());

updateAccounts Job = new updateAccounts ();
system.schedule('Scheduled at '+System.now().format(), nextScheduleTime, Job );

Execute this i workbench after one min, go to schedule apex and delete the jobs.