I've been looking at the Spring Boot example for scheduling tasks (https://spring.io/guides/gs/scheduling-tasks/) and reading through some documentation (https://javahunter.wordpress.com/2011/05/05/cronscheduler-in-spring/) and I see that * and ? are used almost interchangeably.
For example, the line
@Scheduled(cron = "0 15 10 ? * *")
and
@Scheduled(cron = "0 15 10 * * ?")
do the exact same thing. So what is the difference between * and ?
The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.
A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule. These fields, separated by white space, can contain any of the allowed values with various combinations of the allowed characters for that field.
Cron expressions enable us to schedule tasks to run periodically at a specific date and time. After its introduction in Unix, other Unix-based operating systems and software libraries (including the Spring Framework) adopted its approach for task scheduling.
There is no need to use @Async. Just use fixedRate attribute of @Scheduled instead of fixedDelay. Spring will make another invocation on the method after the given time regardless of any call is already being processed.
The tutorial is outdated. The symbol ?
means exactly the same as the symbol *
.
As of Spring version 3.1.2.RELEASE, the call hierarchy is the following:
CronTrigger(String)
calls the constructor CronSequenceGenerator(String)
CronSequenceGenerator(String)
calls parse(String)
parse(String)
calls setDays(BitSet bits, String field, int max)
.Its implementation is clear:
private void setDays(BitSet bits, String field, int max) { if (field.contains("?")) { field = "*"; } setNumberHits(bits, field, 0, max); }
So, if ?
, then *
.
asterix stands for all possible values. question marks should be used for non specific value
*("all values") - used to select all values within a field. For example, "" in the minute field means *"every minute".
? ("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but don't care what day of the week that happens to be, I would put "10" in the day-of-month field, and "?" in the day-of-week field. See the examples below for clarification.
Copied from the tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With