Schedule Hourly Batch Using Cron Expression – Start on Abritrary Day of Month

Can we schedule a batch apex using Cron expression starting from some arbitrary day of the month, say starting from 9th of this month I need to schedule an hourly batch.

Answer

My answer here is I’m assuming when you say ‘random’ you mean, you need the flexibility to allow your users to pick any start date they want to commence the hourly job, which will the run indefinitely.

The Cron expression will either define a specific time to run the job or a reoccuring one, by use of the wild card characters. It does not as far as I can see have the ability to define a start time/date for a reocurrance to start in one expression. So my approach would be to have specific schedule for your random day and then have that commence the hourly schedule.

The following will create a Schedule to run every hour, starting on the next hour from submission.

System.schedule('Hourly', '0 0 * * * ?', new MyHourlySchedule() );

Given this, create a schedule class that can be scheduled on the day you need.

public with sharing class MyScheduleStart implements Schedulable
{
    public void execute(SchedulableContext ctx) 
    {
        System.schedule('Hourly', '0 0 * * * ?', new MyHourlySchedule() );  
    }
}

To schedule a specific date and time for the above.

System.schedule('Start', '0 0 0 10 9 ? 2013' , new MyScheduleStart() );

This will start your hourly schedule on the 10th of September 2013.

Attribution
Source : Link , Question Author : codebandit , Answer Author : Brian Miller

Leave a Comment