文章目录
前言
一、添加注解
二、编写定时任务类
前言
在我们的项目中,经常会需要定时去查询或者更新一些数据,如果每次手动查询或更新会占用大量的时间并且效率很低,使用定时任务可以轻松地在你需要执行的时间段自动化执行某个方法实现功能。
提示:以下是本篇文章正文内容,下面案例可供参考
一、添加注解
在springboot项目的启动类上面添加定时任务注解
//开启定时任务
@EnableScheduling
public class StaApplication {
public static void main(String[] args) {
SpringApplication.run(StaApplication.class, args);
}
}
二、编写定时任务类
代码如下(示例):
//将该类交给spring管理
@Component
public class ScheduledTask {
//注入你自己要调用的方法所在的类交给spring管理
@Autowired
private StatisticsDailyService staService;
@Autowired
private StatisticsDailyController statisticsDailyController;
// 0/5 * * * * ?表示每隔5秒执行一次这个方法
@Scheduled(cron = "0/5 * * * * ?")
public void task1() {
System.out.println("**************task1执行了..");
}
//在每天凌晨1点,把前一天数据进行数据查询添加
@Scheduled(cron = "0 0 1 * * ?")
public void task2() {
//这里可以写需要执行定时任务的方法
staService.getMember(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
}
}
关于定时任务的注解里面的cron参数,是需要指定的时间格式,推荐一个网站自动生成你要指定的时间
https://www.pppet.net/
springboot添加定时任务就是这么简单,注解就可以搞定。