Issue
I need my task to run every 59 seconds from 9am to 6pm, I mean not at 59 seconds of every minute, but 59 seconds after the previous run ends. So i set such a cron to my sheduler */59 * 9-21 * * *
There is a code
@Scheduled(cron = "*/59 * 9-21 * * *")
public void schedule() {
try {
log.info("Scheduler starts!");
} catch (Exception e) {
log.error("Error was caught in scheduler", e);
}
}
And that's what I see in log:
2022-02-09 16:01:00.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:01:59.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:02:00.001 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:02:59.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:03:00.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:03:59.001 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:04:00.001 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:04:59.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:05:00.001 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:05:59.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:06:00.001 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:06:59.002 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
2022-02-09 16:07:00.001 | spring-vault-ThreadPoolTaskScheduler-1 | INFO | com.app.MyScheduler [ / ] - Scheduler starts!
Why does it work in such way and duplicate run at 59 and 00 seconds of each minute? Is my cron wrong?
UPD: I'm using grails 4.0.1
Solution
I think there is a bug in the scheduler.
With the following test code You will see that 2 schedules occur when the current time is in the second 59 on in second 00.
Set<String> x = new HashSet<>();
List<LocalDateTime> y = new ArrayList<>();
while (true) {
var expression = CronExpression.parse("*/59 * 9-21 * * *");
final LocalDateTime now = LocalDateTime.now();
y.add(now);
x.add(expression.next(now).toString());
System.out.println(x);
Thread.sleep(500);
if (x.size() > 2){
break;
}
}
System.out.println(x);
I obtained 3 results
[2022-02-09T15:58:59, 2022-02-09T15:59:59, 2022-02-09T15:59]
For the following dates:
I've tested this with Spring Boot version 2.6.3.
Answered By - pringi Answer Checked By - Cary Denson (WPSolving Admin)