SpringBoot 定时任务遇到的坑
|
前言 springboot已经支持了定时任务Schedule模块,一般情况已经完全能够满足我们的实际需求。今天就记录一下我使用 schedule 时候踩的坑吧。 想要使用定时,我们首先要开启支持,其实就是在启动类上面加个注解就 Ok。
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
这篇博客的主题是记录踩的坑,具体定时任务怎么使用我就不写了,有需要的参考我的博客 Spring定时任务 。 今天踩的这个坑和 cron 表达式有关,我们就先来看看 cron 表达式的解释吧: Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义 解释 * 第一位,表示秒,取值0-59 注: 这个是官方解释 0 0 3 * * ? 每天3点执行 在此我要说明,springBoot 中的 schedule 支持的 cron 表达式和这个不太相符,官方说的星期表示,1是周天,依次类推,但是我在测试过程中,1实际上代表的就是周一,口说无凭 那我就来贴代码和测试结果吧.
@Component
@EnableScheduling
public class Task {
private static final Logger LOGGER = MyLogger.getLogger(Task.class);
@Scheduled(cron = "0 46 20 ? * 1")
public void task() {
LOGGER.info("听说今天是周日");
}
测试结果: 2017-05-08 20:46:00.006 INFO 18838 --- [pool-1-thread-1] com.yiyexy.task.Task : 听说今天是周日 按照上面的解释来讲,第六域是星期,并且值是1那么代表是周日运行,但是我的运行结果表明是周一运行,我在此表示很无奈。 最后我觉得用单词来表示周几,这样就不会出这种问题了,于是
@Component
@EnableScheduling
public class Task {
private static final Logger LOGGER = MyLogger.getLogger(Task.class);
@Scheduled(cron = "0 49 20 ? * MON")
public void task() {
LOGGER.info("听说今天是周日");
}
}
测试结果: 2017-05-08 20:49:00.005 INFO 18864 --- [pool-1-thread-1] com.yiyexy.task.Task : 听说今天是周日 好了,这个坑就记录到这吧,最后奉上一句,时间是检验真理的唯一标准。 好了,下面看下Spring Boot 定时任务的使用 本文介绍在 Spring Boot 中如何使用定时任务,使用非常简单,就不做过多说明了。 下面是代码类:
package org.springboot.sample.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* 定时任务配置类
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年3月21日
*/
@Configuration
@EnableScheduling // 启用定时任务
public class SchedulingConfig {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Scheduled(cron = "0/20 * * * * ?") // 每20秒执行一次
public void scheduler() {
logger.info(">>>>>>>>>>>>> scheduled ... ");
}
}
总结 以上所述是小编给大家介绍的SpringBoot 定时任务遇到的坑,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的! (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
