在SpringBoot中可以通過@Scheduled 注解來定義一個定時任務, 但是有時候你可能會發現有的定時任務到時間了卻沒有執行,但是又不是每次都不執行,這是怎麼回事?
下面這段代碼定義了一個每隔十秒鐘執行一次的定時任務:
@Component
public class ScheduledTaskDemo {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskDemo.class);
@Scheduled(cron = "0/10 * * * * *")
public void execute() {
logger.info("Scheduled task is running... ...");
}
}
複制代碼
此時啟動SpringBoot應用, 可以在控制台看到這個定時任務每隔10秒鐘列印一條log
2017-12-21 22:20:20.832 INFO 7424 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8000 (http)
2017-12-21 22:20:20.859 INFO 7424 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 12.134 seconds (JVM running for 14.156)
2017-12-21 22:20:30.002 INFO 7424 --- [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : S