SpringBoot定时任务处理
- 项目开发当中会有关于重复执行的操作,人工处理费事麻烦,稳定性不高,效率不高,此时就需要定时任务来进行精细化处理。使用的定时任务处理的几个优势(效率高,稳定性高,无感化处理)。
业务层代码
注意层级目录!!!一定不要建错了
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
@MapperScan("cn/oms/modules/jianZhiWang/mapper/dailyTask/dailyAutoRunMapper")
public class AutoRun {
@Autowired
private dailyAutoRunMapper taskMapper;
private static AutoRun autoRun;
@PostConstruct
public void init(){
autoRun = this ;
autoRun.taskMapper = this.taskMapper;
}
//3.添加定时任务
//@Scheduled(cron = "0/5 * * * * ?")
//或直接指定时间间隔,例如:5秒
@Scheduled(cron = "0 0 0 * * ?")
private void configureTasks() {
//去写一个专门修改状态的mapper,写一个方法,替换这里面所有的taskMapper和updateById方法
autoRun.taskMapper.updateDaily();
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}
1.在类上加注解
@Configuration
//1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling
// 2.开启定时任务
@MapperScan("cn/oms/modules/jianZhiWang/mapper/dailyTask/dailyAutoRunMapper")
//3.按照路径进行接口注入,可以在注入报错找不到此接口错误上试试
2.封装一个静态的调用方法
private static AutoRun autoRun;
在调用mapper方法时使用
3.初始化调用方法与赋值
@PostConstruct public void init(){ autoRun = this ; autoRun.taskMapper = this.taskMapper; }
@PostConstruct:
在项目启动时初始常用在方法上作为初始化方法
4.调用定时任务
@Scheduled(cron = "0 0 0 * * ?") private void configureTasks() { //去写一个专门修改状态的mapper,写一个方法,替换这里面所有的taskMapper和updateById方法 autoRun.taskMapper.updateDaily(); System.err.println("执行静态定时任务时间: " + LocalDateTime.now()); }
@Scheduled(cron = "0 0 0 * * ?"):
定时执行,此内容为每日零点零分零秒执行
@Scheduled(cron = "0/5 * * * * ?"):
间隔执行,此内容为每间隔5秒执行一次
逻辑层代码
@Mapper
@Component
public interface dailyAutoRunMapper {
@Update("UPDATE user_daily set task_state = 1 where task_state = 0")
void updateDaily();
}
@Mapper:
不需要在spring配置中设置扫描地址,通过扫描mapper.xml生成Bean自动注入到实现类当中
@Component:
表示此接口交给spring容器进行管理,应用于中立类