Search code examples
javacroncronexpression

How to run a job from 20.35 until 23.35 every 30 minutes, some days a week?


I am facing a problem with cron expression. I have to ran a method from Thursday to Sunday by every 30 minutes. It time will start from 20:35 min till 23:35 min.

Cron expression:

"0 35/30 20-23 ? * THU-SUN";

As per my understanding; My method will invoke at 20:35 min at Thursday by every 30 minutes till Sunday.

My Expectation:

Method will invoke as per below timings:

Thu May 19 20:35:00 IST 2016
Thu May 19 21:05:00 IST 2016
Thu May 19 21:40:00 IST 2016

But; Method get invokes by below timings:

Thu May 19 20:35:00 IST 2016
Thu May 19 21:35:00 IST 2016
Thu May 19 22:35:00 IST 2016

Can anyone help me out. Why cron expression evaluating by every 1 hour.??

Here is code example:

@Scheduled(cron="0 35/30 20-23 ? * THU-SUN")
  public void startInboundSFTPChannel(){
      logger.info("Cron job started....");
      downloadSftpFilesController();
  }

Solution

  • If you want the command to run from 20.35 to 23.35 every day, from Thursday to Sunday, you can define it in two steps:

    35   20    ? * THU-SUN
    5-59 21-23 ? * THU-SUN
    

    There is no easy way to set this up in just a cron expression, because you don't want it to run at 20.05.

    That is: at 20 , run at the minute 35. At 21 to 23 h, every 30 minutes with an offset of 5 minutes.


    I based my answer on this format:

     +---------------- minute (0 - 59)
     |  +------------- hour (0 - 23)
     |  |  +---------- day of month (1 - 31)
     |  |  |  +------- month (1 - 12)
     |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
     |  |  |  |  |
     *  *  *  *  *  command to be executed