javaquartz-scheduler

Java Quartz get nextFireTime from cron expression


I'm trying to calculate next execution time for cronExpression using Java Quartz but always getting null for nextFireTime property.

Cron expression seems valid. and I'm using version 2.3.2 for org.quartz-scheduler

what I'm doing wrong ?


    public LocalDateTime cronExpression(String cronExpression, LocalDateTime startDate) {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .startAt(Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant())).
                    build();

            Date nextExecutionTime = trigger.getNextFireTime();
            return nextExecutionTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        } catch (ParseException e) {
            LOGGER.debug("Error parsing cron expression {}", e.getMessage());
        } catch (Exception e) {
            LOGGER.debug("Unexpected error {}", e.getMessage());
        }
        return null;
    }


    @Test
    void test() throws ParseException {
        String cronExpression = "0 0 10 1/1 * ? *";
        LocalDateTime startDate = LocalDateTime.of(2024, 4, 1, 15, 0);

        LocalDateTime nextExecutionTime = jobSchedulingService.calculateNextExecutionTime(cronExpression, startDate);

        assertNotNull(nextExecutionTime);
        assertEquals(startDate.plusHours(1), nextExecutionTime);
    }



Solution

  • Since you have not scheduled job details and trigger with the Quartz scheduler, it will always return you with a null value when getNextFireTime() is invoked on the trigger.

    If you simply want to get the next fire time by providing a cron expression and a date, you can use getNextValidTimeAfter() in CronExpression. However, this will not consider any misfire instructions which you may have configured on the trigger itself and current state of the job.

    Example:

    LocalDateTime startDate = LocalDateTime.of(2024, 4, 1, 15, 0);
    
    // Cron expression: 10AM every day
    CronExpression cron = new CronExpression(0 0 10 1/1 * ? *);
    
    // Result = 2024-04-02T10:00
    Date nextDate = cron.getNextValidTimeAfter(Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()));