Friday, July 1, 2016

How to run apex job in certain intervals

Hello Everyone,

We have two limitation on salesforce 

  1. We can schedule job once daily/weekly/monthly from UI.
  2. We can only have 100 scheduled job in our org.
Recently I was working to run a job on leads in every four hours with different group of inputs. Every company has his own new fields and criteria. So I ended up with hitting the 100 job limit. My each lead group will need 6 job to run every day and then I ended up with only supporting 16 lead group based on the company.

So I thought of passing an interval to the scheduler which some of us already know but it seems it wont delete the job it has only next run as blank









So you will be hitting the 100 limit . See here





















So I thought to remove the jobs where next-run is empty 

global class TestSchedulable implements Schedulable{
  Integer intervalMinutes;
  String jobName
  global TestSchedulable (String jName,Integer intervalMin){
        intervalMinutes = intervalMin;
        jobName = jName;
  }
  global void execute(SchedulableContext SC) {
        DateTime now  = DateTime.now();
        DateTime nextRunTime = now.addMinutes(intervalMinutes);
        String cronString = '' + nextRunTime.second() + ' ' +                                                                                        nextRunTime.minute() + ' ' + 
                                     nextRunTime.hour() + ' ' + nextRunTime.day() + ' ' + 
                                     nextRunTime.month() + ' ? ' + nextRunTime.year(); 
        System.schedule(jobName + '-' + now.format(), cronString, new                                                                    TestSchedulable (jobName ,intervalMinutes));
         TestSchedulable.removePreviousJob();
  }
     @future     global static void removePreviousJob(){  
          // you may pass the job name and get the id for that job only as well. Below query will remove any job
         // where next-run is null          for(CronTrigger job : [SELECT Id, NextFireTime FROM CronTrigger WHERE NextFireTime = NULL ]){               System.abortJob(job.Id);           }      }
}


Tips on passing Salesforce AI Associate Certification

  🌟 Motivation to Pursue the Salesforce AI Associate Certification 🌟 The world of technology is in a state of perpetual evolution, and on...