SpringBoot 定时器总结

目录

基于@Scheduled的定时器

cron配置在类中

cron在配置文件中

cron配置在数据库中

支持动态修改cron的定时器(SchedulingConfigurer)


基于@Scheduled的定时器

这个很简单,使用和这个注解,配置一个cron表达式,在 主类中增加一个注@EnableScheduling

即可。

这种定时器 cron表达式位置不同,分成三种。

cron配置在类中

例如:

    @Scheduled(cron = "*/3 * * * * ?")
    public void demo2(){
        System.out.println("property cron test!");
    }

启动即可跑起来,问题就是修改cron必须重新编译。

cron在配置文件中

例如

    @Scheduled(cron = "${demo.test}")
    public void demo(){
        System.out.println("property cron test!");
    }

需要在配置文件中配置:

demo:
  test: '*/3 * * * * ?'

这种如果修改cron的话,不需要编译,但是如果需要cron生效的话,需要重启项目。

cron配置在数据库中

例如:

 @Scheduled(cron = "#{@getCron}")
    public void cancel() {
        cancelDetail();
    }

这里需要配置一个配置类,如下:

@Configuration
public class CronConfig {

    @Autowired
    private SystemSettingsDao systemSettingsDao;


    @Bean
    public String getCron() {
        return systemSettingsDao.getSystemSettings(
                "key").getPropertyValue();
    }
}

这样的话,在系统启动的时候就会去加载con表达式,好处就是我们可以把多个配置项目放到一个数据库表中,集中修改,缺点还是需要重启系统使得cron生效。

支持动态修改cron的定时器(SchedulingConfigurer)

具体实现方式如下:

定义一个定时器类TestSchedulerTask 实现接口 SchedulingConfigurer,实现其中configureTasks()方法,定义触发器,在每次执行后查询最新的cron,既可支持动态cron修改而不用重启系统。

如下:

package com.iflytek.cityinsuredmonitorreport.scheduler;

import com.iflytek.cityinsuredmonitorreport.dao.SystemSettingsDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @Program: 
 * @Description:
 * @Author: 
 * @Create: 2021-08-24 16:12
 */
@Component
@Lazy(value = false)
public class TestSchedulerTask implements SchedulingConfigurer {

    private static final Logger log = LoggerFactory.getLogger(TestSchedulerTask .class);

    private static String cron;

    @Autowired
    private SystemSettingsDao systemSettingsDao;

    @Autowired
    private  DutyService dutyService;

    //初始获取cron
    @PostConstruct
    public void cronInit() {
        cron = getCronValue();
        log.info("cron:{}", cron);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            // 任务逻辑
            dutyService.handle();
        }, triggerContext -> {
            // 任务触发,可修改任务的执行周期
            cron = getCronValue();
            log.info("cron-new:{}", cron);
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExec = trigger.nextExecutionTime(triggerContext);
            return nextExec;
        });
    }


    public String getCronValue() {
        return systemSettingsDao.getSystemSettings(
                "cron").getPropertyValue();
    }

}

上述案例中 cron也是从数据库中获取,还可以支持动态修改cron,还不用重启项目。奈斯!

参考博客:

https://blog.youkuaiyun.com/G0_hw/article/details/94877687

https://www.cnblogs.com/lyn20141231/p/12105211.html

https://www.cnblogs.com/mylbs123/p/12894823.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值