I currently have a batch job which I am running every hour. I scheduled the job using CRON syntax in apex. My problem is that I would like to run this job everyhour except from midnight to 1am. I dont know how to write this "except" part in cron apex. This is what I have so far:

global static String scheduletheBatch() {
        datetime nextScheduleTime = system.now().addHours(1);
        integer minute = nextScheduleTime.minute();
        integer second = nextScheduleTime.second ();
        integer hour = nextScheduleTime.hour();
        integer year = nextScheduleTime.year(); 
        integer month = nextScheduleTime.month(); 
        integer day = nextScheduleTime.day();
        string cronvalue = second + ' ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
        string jobName = 'Self Rescheduling Batch Job Scheduler ' + nextScheduleTime.format('hh:mm'); 

        BatchJobScheduler scheduler = new LPP_BatchJobScheduler();
        return system.schedule(jobName, cronvalue, scheduler);

If someone can please help then that would be great. Thanks


You can't exclude things easily, but you can include many hours.

The syntax above runs a job at 7a, 12p and 3p on the hour. Just add the hours you need in there.

String schedule = '0 0 7,12,15 * * ?';

System.schedule('My Job', schedule, new MyClass());
|improve this answer|||||
  • Hello @Sebastian Kessel. If the job runs every hour, why did you put a 30 in the sceond spot? Can you please let me know? – user3688231 Feb 27 at 15:05
  • It was the minute spot, and I forgot to edit it from the code I extracted this from. It is correct now. – Sebastian Kessel Feb 27 at 15:48
  • Thanks! What do you think sbout this solution: where i am checking if the hour is between midnight and 1: datetime nextScheduleTime; integer hourStart = system.now().hour(); if(23<=hourStart && hourStart <= 01){ nextScheduleTime = system.now().addHours(2); } else{ nextScheduleTime = system.now().addHours(1); } // rest of line same as above – user3688231 Feb 27 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.