【Spring Boot】定时任务之Spring Task

1. 前言

本文主要介绍Spring Task的使用、

2. 配置

无需额外的引入,Spring Task集成于spring-context之中。

下面配置定时任务线程池的大小以及线程名称前缀。

@Configuration
@EnableScheduling
public class TaskConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    /**
     * 这里等同于配置文件配置
     * {@code spring.task.scheduling.pool.size=20} - Maximum allowed number of threads.
     * {@code spring.task.scheduling.thread-name-prefix=Job-Thread- } - Prefix to use for the names of newly created threads.
     * {@link org.springframework.boot.autoconfigure.task.TaskSchedulingProperties}
     */
    @Bean
    public Executor taskExecutor() {
        return new ScheduledThreadPoolExecutor(20, new BasicThreadFactory.Builder().namingPattern("Job-Thread-%d").build());
    }
}

3. 使用

@Component
@Slf4j
public class TaskJob {

    /**
     * 按照标准时间来算,每隔 10s 执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void job1() {
        log.info("【job1】开始执行:{}", DateUtil.formatDateTime(new Date()));
    }

    /**
     * 从启动时间开始,间隔 2s 执行
     * 固定间隔时间
     */
    @Scheduled(fixedRate = 2000)
    public void job2() {
        log.info("【job2】开始执行:{}", DateUtil.formatDateTime(new Date()));
    }

    /**
     * 从启动时间开始,延迟 5s 后间隔 4s 执行
     * 固定等待时间
     */
    @Scheduled(fixedDelay = 4000, initialDelay = 5000)
    public void job3() {
        log.info("【job3】开始执行:{}", DateUtil.formatDateTime(new Date()));
    }
}

cron表达式中的6个参数:

  • 秒(0-59)
  • 分(0-59)
  • 时(0-23)
  • 日(1-31)
  • 月(1-12|JAN-DEC)
  • 周(1-7|SUN-SAT)

0/10 * * * * ?中的/

每隔多少秒执行一次,在这里是每隔10秒执行一次。
/ 前面是代表从第几秒开始,在这是从第0秒开始。
/ 后面则是间隔,在这里每两次执行的间隔是10秒。

间隔的数值最好能被60秒整除,因为在到达下一秒时,会立即执行,这会导致还没达到时间间隔就执行了。

比如:0/11 * * * * ?
执行顺序如下:
2020-08-17 08:00:11
2020-08-17 08:00:22
2020-08-17 08:00:33
2020-08-17 08:00:44
2020-08-17 08:00:55
2020-08-17 08:01:00
2020-08-17 08:01:11

在 08:00:55 - 08:01:00 之间只相差5秒就执行了。
而且启动项目之后不会马上执行,
比如你在 08:00:30 启动完成,要等到 08:00:33 才会执行。

如果是间隔执行可以使用fixedDelay达到相同的目的。
fixedDelay不会根据具体时间计算时间间隔,
而是根据启动时间,间隔执行。
比如:fixedRate = 11000 ,08:00:00启动完成,
那么顺序如下:
2020-08-17 08:00:11
2020-08-17 08:00:22
2020-08-17 08:00:33
2020-08-17 08:00:44
2020-08-17 08:00:55
2020-08-17 08:01:06
2020-08-17 08:01:17

如果不想启动后马上执行,还可以加上initialDelay,等待一段时间再执行。

文章作者: 叶遮沉阳
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 叶遮沉阳 !
  目录