当前位置: 移动技术网 > IT编程>开发语言>Java > spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法

spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

串行的定时任务

@component
public class scheduledtimer {
 private logger logger = logger.getlogger(this.getclass());
 /**
 * 定时任务,1分钟执行1次,更新潜在客户超时客户共享状态
 */
 @scheduled(cron="0 0/1 8-20 * * ?")
 public void executeupdatecutask() {
 thread current = thread.currentthread();
 logger.info(" 定时任务1:"+current.getid()+ ",name:"+current.getname());
 }
 @scheduled(cron="0 0/1 8-20 * * ?")
 public void executegetrepaytask() {
 thread current = thread.currentthread();
 logger.info(" 定时任务2:"+current.getid()+ ",name:"+current.getname());
 }
}

并行的定时任务需要添加配置文件

因为spring-boot的目的就是干掉配置文件,我在网上看到的很多都是通过配置文件来实现的,这里通过代码配置实现:

@configuration
public class scheduleconfig implements schedulingconfigurer{
 @override
 public void configuretasks(scheduledtaskregistrar taskregistrar){
 taskscheduler taskscheduler = taskscheduler();
 taskregistrar.settaskscheduler(taskscheduler);
 }
 @bean(destroymethod = "shutdown")
 public threadpooltaskscheduler taskscheduler() {
 threadpooltaskscheduler scheduler = new threadpooltaskscheduler();
 scheduler.setpoolsize(20);
 scheduler.setthreadnameprefix("task-");
 scheduler.setawaitterminationseconds(60);
 scheduler.setwaitfortaskstocompleteonshutdown(true);
 return scheduler;
 }
}

网上教程说的需要在启动类上加上@enablescheduling注解来发现注解@scheduled的任务并后台执行。

可能我没有通过启动类是通过外部tomcat启动的项目,所以没有加这个注解也能实现定时任务

下面看下springboot 定时任务@scheduled注解

需要定时器的地方好像还挺多. 之前项目中有用到使用定时器循环订单时间,然后将超时的订单状态更改.

springboot的@scheduled注解能够很快速完成我们需要的定时任务.

@component
public class exampletimer {
 simpledateformat dateformat = new simpledateformat("hh:mm:ss");  
 /*每100秒执行一次*/
 @scheduled(fixedrate = 100000)
 public void timerrate() {
  system.out.println("我是:timerrate");
 } 
 /*第一次10秒后执行,当执行完后2秒再执行*/
 @scheduled(initialdelay = 10000, fixeddelay = 2000)
 public void timerinit() {
  system.out.println("init : "+dateformat.format(new date()));
 }
 /*每天15:39:00时执行*/
 @scheduled(cron = "0 39 15 * * ? ")
 public void timercron() {
  system.out.println("current time : "+ dateformat.format(new date()));
 }
}

其中需要注意的是:fixedrate和fixeddelay这两个参数开始计时的时间不一样.如果需要调用的方法执行时间比较长, 这时差别就能体现出来.

fixedrate:上一次开始执行时间点后再次执行;

fixeddelay:上一次执行完毕时间点后再次执行;

还发现还有一种方法是调用配置文件的方法.

@scheduled(fixeddelaystring = "${jobs.fixeddelay}")
 public void gettask1() {
 system.out.println("任务1,从配置文件加载任务信息,当前时间:" + dateformat.format(new date()));
 }

总结

以上所述是小编给大家介绍的spring-boot通过@scheduled配置定时任务及定时任务@scheduled注解的方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网