24

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.

3 Answers 3

35

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.

2
  • Hi @Andrew Fawcett, the Hours only accept 0-23 no special characters, Right? One can see that hours do not accept special characters here: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… Commented Aug 12, 2020 at 9:17
  • @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 , - * /
    – Bahman.A
    Commented Jan 19, 2021 at 22:33
4

From the Developer Console, an Apex Scheduler can be scheduled to run every hour :-

RunReport1 m = new RunReport1();
String sch = '0 55 * * * ?'; 
String jobID = system.schedule('RunReport1', sch, m);

RunReport1 is the Apex Scheduler class that implements Schedulable interface. This will be run 55 minutes past every hour. Sequence format for sch is :-

Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year

1

You could also visit my blog where i've made a post to explain th scenario in details http://blog.shivanathd.com/2013/01/run-batch-class-hourly.html

update:

// Cron EXP for hourly schedule 
String CRON_EXP = '0 0 * * * ?'; 
SheduledBatchable sch = new scheduledBatchable(); 
system.schedule('Hourly Example Batch Schedule job', CRON_EXP, sch);
1
  • // Cron EXP for hourly schedule String CRON_EXP = '0 0 * * * ?'; SheduledBatchable sch = new scheduledBatchable(); system.schedule('Hourly Example Batch Schedule job', CRON_EXP, sch); Commented Oct 22, 2013 at 15:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .