开启定时任务
启动类上增加注解
@EnableScheduling // 开启定时任务
通过注解设定定时任务**
/**
* 任务类
*/
@Component
public class MySpringTask {
/**
* 每2秒执行1次
*/
@Scheduled(fixedRate = 2000)
public void fixedRateMethod() throws InterruptedException {
System.out.println("fixedRateMethod:" + new Date());
Thread.sleep(1000);
}
}
使用 Cron 表达式
@Component
public class MySpringTask {
/**
* 在每分钟的00秒执行
*/
@Scheduled(cron = "0 * * * * ?")
public void jump() throws InterruptedException {
System.out.println("心跳检测:" + new Date());
}
/**
* 在每天的00:00:00执行
*/
@Scheduled(cron = "0 0 0 * * ?")
public void stock() throws InterruptedException {
System.out.println("置满库存:" + new Date());
}
}