Search code examples
javaspring-bootspring-scheduled

Spring Boot wakes up too early on scheduled method


I found a strange behaviour on Spring Boot 3. Inside a method noted with @Scheduled I need to get the current time every 10 seconds (0, 10, 20, etc.), but sometimes it seems to be triggered few nanoseconds too early so the "seconds" are not as expected. Code example

@Scheduled(cron = "0/10 * * * * *")
public void job() {
    LocalDateTime now = LocalDateTime.now();
    log.info(":: {} :: {}", now, now.truncatedTo(ChronoUnit.SECONDS));
}

This is what I get:

2022-12-30T14:12:10.012+01:00  INFO 14896 --- [   scheduling-1] com.example.demo301.Job                  : :: 2022-12-30T14:12:10.012881700 :: 2022-12-30T14:12:10
2022-12-30T14:12:20.014+01:00  INFO 14896 --- [   scheduling-1] com.example.demo301.Job                  : :: 2022-12-30T14:12:20.014202300 :: 2022-12-30T14:12:20
**2022-12-30T14:12:29.999+01:00  INFO 14896 --- [   scheduling-1] com.example.demo301.Job                  : :: 2022-12-30T14:12:29.999757 :: 2022-12-30T14:12:29**
2022-12-30T14:12:40.005+01:00  INFO 14896 --- [   scheduling-1] com.example.demo301.Job                  : :: 2022-12-30T14:12:40.005453100 :: 2022-12-30T14:12:40
2022-12-30T14:12:50.012+01:00  INFO 14896 --- [   scheduling-1] com.example.demo301.Job                  : :: 2022-12-30T14:12:50.012125900 :: 2022-12-30T14:12:50

I have created some maven projects from spring initializr with these options:

  • java version 19 / 17
  • 3.0.1 / 2.7.7
  • jar

I let the code run for 1 hour on intellij with openjdk-19 and found this problem with spring boot 3 (both java versions). My original evironment is docker with an image from openjdk, and it seems to happen more frequently but it could just be random. I downgraded to 2.7.7. Looking over the past months (I save a record every 10 second) with spring boot 2.7 in docker (java 15) on another SO, the same problem appeared just a few time so I didn't notice.

I suppose this is a spring problem due to the annotation, and it is java/SO independent. Does anyone found the same issue? I'am not looking to fix the code like adding 1 or 2 milliseconds (horrible), but it doesn't look ok either.

Looking forward a spring boot or java/openjdk fix.


Solution

  • Maybe I mistakenly referred to Spring Boot as guilty, but there is an open issue on Spring Framework about this problem: https://github.com/spring-projects/spring-framework/issues/29735