How to get next run time Spring Scheduling?
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
}
}