一、使用SpringBoot创建定时任务
- 1.pom
- spring默认就集成了定时任务,不需要单独再引入依赖
- 2.启动类增加注解@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
}
}
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 3000)
public void taskService(){
System.out.println("定时任务执行" + System.currentTimeMillis());
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/7dcaa2016f8f4d14b537d130d5646910.png)
二、定时任务使用Quartz表达式
- 1.Quartz表达式编写参考
- 在线生成网站:https://www.bejson.com/othertools/cron/
- 2.代码
@Component
public class ScheduledTasks {
@Scheduled(cron = "1/2 * * * * ? ")
public void taskService(){
System.out.println("定时任务执行" + System.currentTimeMillis());
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/c6bece92c8a64c648cae29a38b1a660e.png)