Friday 16 October 2015

Scheduling Batch Job To Run Every N-Minutes in Salesforce.com


Have you ever wondered or come across scheduling batch job to run every N-Minutes( for example 1 minute or 5 minutes)?
Yes, I have! Since this is not possible to do thru standard Salesforce UI.

Sometimes  in order to do so, we go for scheduling multiple times; for example 11 times if it has to be scheduled every 5 minutes. Here is the next question: Can't it be done in a single scheduling attempt? Yes, it can be. The next is the solution..  


So here is a small code to do so for every 5 minutes. You can customize your logic for every N_minutes. You can execute this piece of code in developer console as well.

DateTime myDateTime = System.Now() ;
System.debug('Sudhir myDateTime:: ' + myDateTime) ;


static Integer iHour = myDateTime.hour() ;

System.debug('Sudhir iHour :: ' + iHour) ;

static Integer iMinute = myDateTime.minute() ;
System.debug('Sudhir iMinute:: ' + iMinute) ;

static Integer iSecond = myDateTime.second() ;
System.debug('Sudhir iSecond:: ' + iSecond) ;

for(Integer i = 0; i < 60 ; i = i + N){ 
    if(iSecond > 59){
        iSecond = 0 ;
    }  
  if(iMinute > 55){
        iMinute = 0 ;
        iHour = iHour + 1 ;
    } else{
        iMinute = iMinute + N ;
    }
    String sExpression = String.valueOf(iSecond) + ' ' + String.valueOf(iMinute) + ' ' + '*' +  ' ' + '*' + ' ' + '*' + ' ' + '?' + ' ' + '*' ;
    System.debug('Sudhir sExpression:: ' + sExpression) ;

     ScheduledBatchJob_APIName oScheduledBatchJob_APIName = new ScheduledBatchJob_APIName () ;
     System.schedule('Comment for Scheduled batch Job' + '-' + i, xpression, oScheduledBatchJob_APIName) ;
}








Happy Apex coding and sharing.. 

No comments:

Post a Comment

Thank you for visiting. Your comments are highly appreciated.