Showing posts with label schedule job. Show all posts
Showing posts with label schedule job. Show all posts

Wednesday, June 6, 2012

How to Schedule job from Schedule Job

Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed based on service availability.

You can only have 25 classes scheduled at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce or programmatically using SOAP API to query the CronTrigger object.

When we schedule a class, cron expression plays an important role to decide the next scheduled time of the class. Please refer the following link for more details about cron expression. http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

In the below code sample the cron expression is built in such a way so that it will not schedule the job in future.I have used the year parameter in cron expression which will not schedule the same class again.

global class scheduledJobController implements Schedulable{
   global void execute(SchedulableContext SC) {
       try {
         // TO DO LOGIC
       }
       catch(Exception e) {
         // TO DO Log error
       }
       finally {
            Datetime currentTime = datetime.now();
            Datetime newTime = currentTime.addSeconds(20);
            // build cron expression
            String sch= String.valueOf(newtime.second()) +' ' + String.valueOf(newtime.minute()) + ' ' + String.valueOf(newTime.hour()) + ' ' + String.valueOf(newTime.day()) + ' ' + String.valueOf(newTime.month()) + ' ? ' +  String.valueOf(newTime.year());
            scheduledJobController scheduleObject = new scheduledJobController();
            Id sId = system.schedule('scheduledJobController'+newTime , sch, scheduleObject );  
       }
   }
}