springboot中定时任务简单版
遇到了一个问题(@Scheduled定时任务不生效???)
定时任务可以有很多的写法,下面这个方法我觉的最简单,如果你的项目用的是spring boot框架,就可以三步完成:
一,添加@EnableScheduling注解到入口类声明上面
/**
* 启动
*
*/
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
}
这里是在springboot启动类上添加注解@EnableScheduling
二,创建类,添加@Component注解
@Slf4j
@Component
public class CenturyDebrisQuartz implements CommandLineRunner {
//毫秒 10分钟
private final static String fixedDelay = "600000";
@Resource
private ICenturyDebrisService iCenturyDebrisService;
@Override
public void run(String... args) throws Exception {
log.info("归还用户未获得的碎片启动");
iCenturyDebrisService.udpateDebrisFlag();
}
@Scheduled(fixedDelayString = fixedDelay)
public void doSomething() {
log.info("归还用户未获得的碎片启动========十分钟执行一次");
iCenturyDebrisService.udpateDebrisFlag();
}
}
上麦实现CommandLineRunner 接口是在项目启动的时候调用的,会实现一个run方法
三,创建方法,添加@Scheduled注解
@Scheduled(fixedDelayString = fixedDelay)
public void doSomething() {
log.info("归还用户未获得的碎片启动========十分钟执行一次");
iCenturyDebrisService.udpateDebrisFlag();
}
这里的@Scheduled注解里面还有其他属性,也可以使用cron来自定义定时启动时间
从配置文件中读取定时的时间
@Scheduled(cron = "${task.cron.tradeData}")
public void getTradeData() {
}
(这里cron是从配置文件取值,如下)
task:
cron:
tradeData: 0 1 0 * * ?
看似简单,却隐藏着很多坑,一不小心就掉进去了,比如:
(1)此方法不能有参数
(2)此方法不能有返回值
(3)此类中不能包含其他带任何注解的方法(发现新大陆)
违反任何一条,定时都不会生效!
小心别入坑哦!!!!