javacron

Cron Job sixth parameter in Java


I am very new to Java. As my first project, I am going to work with cron job scheduler. I want some clarification on scheduling. I have a code which will run every hour.

  CronTrigger ct = new CronTrigger("cronTrigger", "group2", "0 1/0 * * * ?"); 

I have read the documents about scheduling, but I got confused

In one document i have read like in the below

 ("0 0 * * * ?") 

In some document I read that 1st indicates mins 2nd - hour etc.

Can anyone please explain me this(0 1/0 * * * ?) and also what it means (1/0)?

And I want to run a job in every six hours.

If i give like this (0 */6 * * * ?) whether it will run in every six hours?


Solution

  • If you check in crontab.guru, both of these are almost equivalent:

    *   * * * *
    * 1/0 * * *
    

    This is because X/Y means: starting from X, every Y. That is, all X + Yn. So if you say */2 it will do every 2 hours.

    In this case: 1/0 means "starting from 1, every hour", so it matches from 1 to 23, whereas * matches from 0 to 23.

    Following your question, */6 matches every 6 hour, so it will precisely run at hour 0, 6, 12 and 18.

    Regarding your question on what is the 6th parameter ? doing, I read that:

    I believe that's processed by the CronExpression class which has six constants: minute, hour, day, month, weekday, year. Cron uses minute, hour, day, month, weekday. The addition of the year for the yearly() method seems to be the reason for the extra *.

    So instead of having the common syntax

     +---------------- 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 
    

    With Java you have

       +----------------- minute (0 - 59)
       |  +-------------- hour (0 - 23)
       |  |  +----------- day of month (1 - 31)
       |  |  |  +-------- month (1 - 12)
       |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
     # |  |  |  |  |  +-- year                       <-- this is extra !!
       |  |  |  |  |  |
       *  *  *  *  *  * command to be executed 
    

    This last parameter can have a value as well, but in your case it specifies ?. As for what I read in crontab.guru, it means:

    ? blank (non-standard)

    So I would schedule it normally with the 5 usual parameters and then add ? at the end so that it runs in all years.