18

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.

27

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.

1

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

0

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);
  • // Cron EXP for hourly schedule String CRON_EXP = '0 0 * * * ?'; SheduledBatchable sch = new scheduledBatchable(); system.schedule('Hourly Example Batch Schedule job', CRON_EXP, sch); – Shivanath D Oct 22 '13 at 15:39

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.