I'm trying to get the next execution of a cron in spring. Previously, I was using CronSequenceGenerator, but since it is deprecated, I'm trying to update to CronExpression. I use a ZonedDateTime as the current date to find the next one.
String cron = "0 0 21 * * MON-FRI";
CronExpression cronExpression = CronExpression.parse(cron);
ZonedDateTime date = ZonedDateTime.parse("2021-04-12T21:00-04:00[America/Montreal]");
Instant next = cronExpression.next(date.toInstant());
The problem is that when I try, I always get an exception, no matter the cron.
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek
at java.base/java.time.Instant.get(Instant.java:565)
at org.springframework.scheduling.support.CronField$Type.get(CronField.java:200)
at org.springframework.scheduling.support.BitsCronField.nextOrSame(BitsCronField.java:180)
at org.springframework.scheduling.support.CronExpression.nextOrSameInternal(CronExpression.java:264)
at org.springframework.scheduling.support.CronExpression.nextOrSame(CronExpression.java:252)
at org.springframework.scheduling.support.CronExpression.next(CronExpression.java:245)
[...]
I don't know why I'm getting this error. If I try to just pass the ZonedDateTime (as it is a Temporal and cronExpression.next takes Temporal) I get a compilation error.
java: incompatible types: inference variable T has incompatible bounds
lower bounds: java.time.Instant,java.time.chrono.ChronoZonedDateTime<?>,java.lang.Object,java.time.temporal.Temporal,java.lang.Comparable<? super T>
lower bounds: java.time.ZonedDateTime
Can anyone tell me what I'm doing wrong?
I'm using Java11 with spring-context 5.3.20
Here's the documentation I'm consulting: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronExpression.html https://docs.oracle.com/javase/8/docs/api/java/time/temporal/Temporal.html?is-external=true
CodePudding user response:
As I mentioned in my comment, Instant
has no DayOfWeek
.
String cron = "0 0 21 * * MON-FRI";
CronExpression cronExpression = CronExpression.parse(cron);
ZonedDateTime next = cronExpression.next(ZonedDateTime.now());
CodePudding user response:
Using an OffsetDateTime instead of ZonedDateTime solved the problem, but I'm still not sure why. Maybe there's a problem in the conversion from ZonedDateTime to Instant?
Trying to skip the conversion to Instant, no matter the type (ZonedDateTime, LocalDateTime, OffsetDateTime) always resulted in a compilation error.