Search code examples
springscheduled-tasksjob-schedulingspring-scheduled

How to get next run time Spring Scheduling?


I am working on a scheduling project which executes multiple jobs at regular intervals. I am using a cron scheduling as in the example below. The jobs are getting executed successfully no problems. However for a requirement I want to calculate and persist the next run time of the Scheduled job in DB. Is there a solution to get next and previous fire times of jobs for the configuration below?

Example configuration:

import java.util.Date;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class DemoServiceBasicUsageCron
{   
    @Scheduled(cron="1,3,30,32 * * * * ?")
    public void demoServiceMethod()
    {
        System.out.println("Curent date time is - "+ new Date());
    }

}

Solution

  • You can use CronExpression for Spring Framework 5.3 and newer. Use CronSequenceGenerator for older versions. Both of them have same methods. But CronSequenceGenerator is deprecated.

    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.scheduling.support.CronExpression;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    import java.util.Date;
    
    @Component
    public class MyJob {
    
        public static final String CRON_EXPRESSION = "0 0 5 * * *";
    
        @PostConstruct
        public void init() {
            //Update: Resolve compile time error for static method `parse`
            CronExpression cronTrigger = CronExpression.parse(CRON_EXPRESSION);
    
            LocalDateTime next = cronTrigger.next(LocalDateTime.now());
    
            System.out.println("Next Execution Time: " + next);
        }
    
        @Scheduled(cron = CRON_EXPRESSION)
        public void run() {
            // Your custom code here
        }
    }