spring Boot编写定时任务相关方法

本文介绍了如何在SpringBoot项目中创建定时任务,强调了其在提高效率和稳定性方面的优势。主要步骤包括在业务层类上添加注解,封装静态调用方法,初始化方法和调用定时任务。同时提到了逻辑层代码,说明了无需额外配置扫描地址,Spring容器会自动管理并注入接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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容器进行管理,应用于中立类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值