Spring Boot(五):开启quartz定时任务

除了Java 中内置的定时任务之外,一般都使用quartz的cron 表达式做定时任务
一、quartz定时任务

cron 的格式 : “* * * * * ?” 至少有6个(也可以7个) 由空格分隔的时间元素
含义说明:

          "0 */1 * * * ?"      每分钟执行一次(循环)    斜杠代表轮询执行
           "30 40 17 * * ?"   定时执行时间(每天的 17:40:30 执行)  
  格式:[秒] [分] [小时] [日] [月] [周] [年] 

可参考:cron在线表达式生成 快速生成自己想要的结果

二:在spring boot 中使用 quartz
1、不需要引入依赖,spring中自带的有
首先在启动类上加一个注解 @EnableScheduling 启用定时任务

@SpringBootApplication
@EnableScheduling
public class Application {
    private static Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args){
    SpringApplication.run(Application.class,args);
        logger.info("==========SpringBoot Start==========");
    }
}

2、在application.yml文件中可配置

#############定时器配置项##############
user:
    env:
        scheduled:
            testTime: "*/1 * * * * ?"     #测试:一秒钟
            jcTime: "0 */1 * * * ?"        #基础资料:一分钟
            bhdTime: "30 21 15 * * ?" #报货单:每天的 15:21:30

3、在定时执行类中使用

@Component
public class TimerTest {

        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

        //${user.env.scheduled.jcTime}
        @Scheduled(cron="${user.env.scheduled.testTime}")
        public void timerRate(){
            System.out.println("每秒执行: "+ dateFormat.format(new Date()));
        }
}

通过在方法上添加 @Scheduled注解,表名该方法是一个调度任务

* @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
* @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
* @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
* @Scheduled(cron="30 21 15 * * ?" ) :通过cron表达式定义规则   每天的 15:21:30执行

总结:
在springboot创建定时任务比较简单,只需2步:

  • 在程序的入口加上@EnableScheduling注解。
  • 在定时方法上加@Scheduled注解。
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值