spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法
串行的定时任务
@Component publicclassScheduledTimer{ privateLoggerlogger=Logger.getLogger(this.getClass()); /** *定时任务,1分钟执行1次,更新潜在客户超时客户共享状态 */ @Scheduled(cron="00/18-20**?") publicvoidexecuteUpdateCuTask(){ Threadcurrent=Thread.currentThread(); logger.info("定时任务1:"+current.getId()+",name:"+current.getName()); } @Scheduled(cron="00/18-20**?") publicvoidexecuteGetRepayTask(){ Threadcurrent=Thread.currentThread(); logger.info("定时任务2:"+current.getId()+",name:"+current.getName()); } }
并行的定时任务需要添加配置文件
因为spring-boot的目的就是干掉配置文件,我在网上看到的很多都是通过配置文件来实现的,这里通过代码配置实现:
@Configuration publicclassScheduleConfigimplementsSchedulingConfigurer{ @Override publicvoidconfigureTasks(ScheduledTaskRegistrartaskRegistrar){ TaskSchedulertaskScheduler=taskScheduler(); taskRegistrar.setTaskScheduler(taskScheduler); } @Bean(destroyMethod="shutdown") publicThreadPoolTaskSchedulertaskScheduler(){ ThreadPoolTaskSchedulerscheduler=newThreadPoolTaskScheduler(); scheduler.setPoolSize(20); scheduler.setThreadNamePrefix("task-"); scheduler.setAwaitTerminationSeconds(60); scheduler.setWaitForTasksToCompleteOnShutdown(true); returnscheduler; } }
网上教程说的需要在启动类上加上@EnableScheduling注解来发现注解@Scheduled的任务并后台执行。
可能我没有通过启动类是通过外部tomcat启动的项目,所以没有加这个注解也能实现定时任务
下面看下springboot定时任务@Scheduled注解
需要定时器的地方好像还挺多.之前项目中有用到使用定时器循环订单时间,然后将超时的订单状态更改.
springboot的@Scheduled注解能够很快速完成我们需要的定时任务.
@Component publicclassExampleTimer{ SimpleDateFormatdateFormat=newSimpleDateFormat("HH:mm:ss"); /*每100秒执行一次*/ @Scheduled(fixedRate=100000) publicvoidtimerRate(){ System.out.println("我是:timerRate"); } /*第一次10秒后执行,当执行完后2秒再执行*/ @Scheduled(initialDelay=10000,fixedDelay=2000) publicvoidtimerInit(){ System.out.println("init:"+dateFormat.format(newDate())); } /*每天15:39:00时执行*/ @Scheduled(cron="03915**?") publicvoidtimerCron(){ System.out.println("currenttime:"+dateFormat.format(newDate())); } }
其中需要注意的是:fixedRate和fixedDelay这两个参数开始计时的时间不一样.如果需要调用的方法执行时间比较长,这时差别就能体现出来.
fixedRate:上一次开始执行时间点后再次执行;
fixedDelay:上一次执行完毕时间点后再次执行;
还发现还有一种方法是调用配置文件的方法.
@Scheduled(fixedDelayString="${jobs.fixedDelay}") publicvoidgetTask1(){ System.out.println("任务1,从配置文件加载任务信息,当前时间:"+dateFormat.format(newDate())); }
总结
以上所述是小编给大家介绍的spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!