Boyu
Boyu

Reputation: 21

Scheduled job in Spring Boot

I have a cron expression set in the application properties file as follows:

report.monthlyScheduleTime=0 10 07 1W * ?

and annotated like the following,

@Scheduled(cron = "${report.monthlyScheduleTime}", zone="${report.scheduleTimeZone}")

But when ran the application, I got the following exception.

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'ReportJob': For input string: "1W".

Spring Boot seems to not accept 1W defined in the cron expression. Any idea why?

Upvotes: 2

Views: 2457

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Spring Boot seems to not accept 1W defined in the cron expression. Any idea why?

1W is specific to Quartz, but you are not using Quartz.


Your cron expression (0 10 07 1W * ?) is correct based on the Quartz documentation:

The ‘W’ is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify “15W” as the value for the day-of-month field, the meaning is: “the nearest weekday to the 15th of the month”.

But the pattern 1W is specific to Quartz.

With @Scheduled, you are using Spring's own scheduling support. This allows expression based on Crontab pattern but has no support for 1W.

So you either need to actually use Quartz or modify your cron expression. If you want to use Quartz, in Spring documentation on scheduling, the section "Using the Quartz Scheduler" describes Spring's support for Quartz. However, if you want to modify cron expression, you can refer to CronSequenceGenerator.

Upvotes: 2

yairo
yairo

Reputation: 103

not sure what cron you wanted to create, but maybe these examples will help you understand your issue:

Example patterns:

"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight

Upvotes: 0

Related Questions