1.在Spring boot启动类上添加注解:
@EnableScheduling
2.在需要执行定时任务的类上加@Component注解,在需要执行的方法上加@Scheduled(cron = "0/2 * * * * *")注解
@Component
public class SpringTaskTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringTaskTest.class);
/**
* 每隔2秒执行一次
*/
@Scheduled(cron = "0/2 * * * * *")
public void task1() {
LOGGER.info("--------------------task1开始--------------------");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LOGGER.info("--------------------task1结束--------------------");
}
}
参考:
https://blog.csdn.net/qq_38628046/article/details/113484979