boot定时任务开启和关闭 spring_Spring Boot 2.x实战之定时任务调度

> 本文首发于个人网站:[Spring Boot 2.x实战之定时任务调度](http://www.javaadu.online/?p=670)

在后端开发中,有些场景是需要使用定时任务的,例如:定时同步一批数据、定时清理一些数据,在Spring Boot中提供了`@Scheduled`注解就提供了定时调度的功能,对于简单的、单机的调度方案是足够了的。这篇文章准备用实际案例看下`@Scheduled`的用法。

## 开发实战

1. 新建Spring Boot工程,主pom文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>4.0.0org.springframework.bootspring-boot-starter-parent2.2.2.RELEASEonline.javaadu.schedulescheduledemo0.0.1-SNAPSHOTscheduledemoDemo project for Spring Boot1.8org.springframework.bootspring-boot-starterorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestorg.junit.vintagejunit-vintage-engineorg.springframework.bootspring-boot-maven-plugin

2. 新建定时任务组件,使用`@Scheduled`注解修饰要调度的方法,在该方法中会打印当前的时间。

package online.javaadu.schedule.scheduledemo;      import org.slf4j.Logger;   import org.slf4j.LoggerFactory;   import org.springframework.scheduling.annotation.Scheduled;   import org.springframework.stereotype.Component;      import java.text.SimpleDateFormat;   import java.util.Date;      @Component   public class ScheduledTasks {          private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);          private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");        //第一次执行之前延后10秒钟;后续每隔5秒执行1次       @Scheduled(fixedRate = 5000, initialDelay = 10000)       public void reportCurrentTime() {           log.info("The time is now {}", dateFormat.format(new Date()));       }   }

3. 在ScheduledemoApplication中开启定时调度能力——即开启`@Scheduled`注解的定时调度功能,并在系统刚起来的时候打印一行日志,用来体现上一步中的initialDelay的作用。

package online.javaadu.schedule.scheduledemo;      import org.slf4j.Logger;   import org.slf4j.LoggerFactory;   import org.springframework.boot.SpringApplication;   import org.springframework.boot.autoconfigure.SpringBootApplication;   import org.springframework.scheduling.annotation.EnableScheduling;      import java.text.SimpleDateFormat;   import java.util.Date;      @SpringBootApplication   @EnableScheduling   public class ScheduledemoApplication {      private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);   private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");      public static void main(String[] args) {   SpringApplication.run(ScheduledemoApplication.class, args);   log.info("---The time is now {}", dateFormat.format(new Date()));   }      }

4. 点击运行后,该demo的运行结果如下,可以看出,23:15:35应用启动,过了10秒钟定时调度任务才开始执行,然后是每隔5秒钟打印一次时间。

e8e14c2ff97276a28ac00cbab4899669.png

分析解释

我们一起来看下`@Scheduled`注解的源码,看看除了上面的例子里提供的案例,该注解还有哪些功能呢?

  • cron,可以支持更复杂的时间复杂度
  • zone,解析cron表达式的时候解析时区
  • fixedDelay(和fixedDelayString),两次调度之间需要加一个固定的延迟
  • fixedRate(和fixedRateString),没隔多久需要调度一次
  • initialDelay(和initialDelayString),第一次调度之前需要延迟多久
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Repeatable(Schedules.class)public @interface Scheduled {/** * 特殊的cron表达式,如果设置成这个值,则表示将定时调度器关闭,不再调度。 */String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;/** * cron表达式,可以支持复杂的定时调度需求 */String cron() default "";/** * cron表达式解析的时候,解析依赖的时区 */String zone() default "";/** * 两次调度触发之间暂停的毫秒数,Long类型 */long fixedDelay() default -1;/** * 两次调度触发之间暂停的毫秒数,String类型 */String fixedDelayString() default "";/** * 每隔几毫秒调度一次 */long fixedRate() default -1;/** * 每隔几毫秒调度一次,String类型 */String fixedRateString() default "";/** * 第一次执行之前,延迟多少毫秒 */long initialDelay() default -1;/** * 第一次执行之前,延迟多少毫秒,String类型 */String initialDelayString() default "";}

参考资料

1. [https://spring.io/guides/gs/scheduling-tasks/](https://spring.io/guides/gs/scheduling-tasks/)

2. 《Spring Boot实战》

Spring Boot 2.x系列

1. [Spring Boot 2.x实战之StateMachine](http://www.javaadu.online/?p=655)


本号专注于后端技术、JVM问题排查和优化、Java面试题、个人成长和自我管理等主题,为读者提供一线开发者的工作和成长经验,期待你能在这里有所收获。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值