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.

  • 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.

    Hi @Andrew Fawcett, the Hours only accept 0-23 no special characters, Right? One can see that hours do not accept special characters here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm

    @Cubancoffee the link you posted here, has a table that shows exactly the opposite, the hour part also takes special characters, these are the characters , - * /

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM