記得之前在接觸 Spring 如何運行定期任務時,見到同事寫的 Cron Expression。看著感到不對勁,怎麼好像有問題似的?
一查,原來 Spring @Scheduled
的 Cron Expression 和 Linux 上的有所分別。
Linux 上的 Syntax
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of the month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
│ │ │ │ │ 7 is also Sunday on some systems)
│ │ │ │ │
│ │ │ │ │
* * * * * <command to execute>
來源:維基百科
Spring 的 @Scheduled
┌───────────── second (0-59)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of the month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
│ │ │ │ │ ┌───────────── day of the week (0 - 7)
│ │ │ │ │ │ (0 or 7 is Sunday, or MON-SUN)
│ │ │ │ │ │
* * * * * *
來源:Spring 官網
兩者的分別在於,Spring 的 Annotation @Scheduled
有 6 個 fields, 其中第一個 field 是秒鐘 (Second)。不同於 Linux 上的 cron job 只有 5 個控制時間的 fields, 不包括秒鐘。
若果是用 quartz 的話,還可以控制年份呢。
References
https://en.wikipedia.org/wiki/Cron
http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html