定时任务 - Spring task 介绍及使用

开篇

在平常的业务开发过程当中,可能会须要实现一些周期性定时任务,好比定时同步数据库、定时发送短信 或者 邮件等。java

那么在 Java 中,共有三种定时任务的实现方式:spring

  1. 经过 java.util.Timer、TimerTask 实现。数据库

  2. 经过 Spring 自带的 SpringTask。(Spring 3.0 之后)springboot

  3. 经过 Spring 结合 Quartz 实现。异步

而本文说的是第二种方式 - Spring 定时器。线程

使用

如今开发都是基于 springboot,而在 springboot 中配置 spring task 尤其简单。code

步骤以下:blog

  1. 准备一个 springboot 工程ci

  2. 在启动类上添加 @EnableScheduling 注解开发

    @SpringBootApplication
    @EnableScheduling
    public class DemoApplication {
    }
  3. 在定时执行的方法上添加 @Scheduled(fixedDelay = 3 * 1000) 注解

    @Scheduled(fixedDelay = 3 *1 000)
    public void p1(){
    	System.out.println(Thread.currentThread().getName() + "  p1");
    }

注意: 第三步注解的属性会在后面细讲

@Scheduled 注解

在说注解属性以前, 须要了解下 Spring 定时器的三种工做模式。

1. fixedDelay

当上一次的任务执行完成以后, 再等 3 秒钟, 执行下一次任务。

示意图以下:

配置以下:

@Scheduled(fixedDelay = 3 * 1000)

2. fixedRate

会根据设置的值, 来预计每次任务应该在何时执行。

假定设置的值是 3 秒。那么每一个任务预计执行的时间就是 3 秒钟, 定时任务在 7点 0分 0秒 开始执行。

示意图以下:

配置以下:

@Scheduled(fixedRate = 3 * 1000)

3. cron

假定设置的每 5 秒 执行一次,会每隔 5 秒来看一下,上一个任务是否执行完成。

示意图以下:

配置以下:

@Scheduled(cron = "0/3 * * * * ? ")

思考

问题

了解了 Spring 定时器的三种工做模式后,来思考一个问题,以下面时序图的定时功能?

答案

默认状况下,定时任务是由一个单线程执行的。因此咱们须要定义一个线程池去异步执行定时任务。

具体步骤:

  1. 定义一个线程池

    @Configuration
     @EnableAsync
     public class SchedulerAsyncConfig {
    
     	@Bean
     	public Executor taskExecutor(){
     		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
     		executor.setMaxPoolSize(200);
     		executor.setCorePoolSize(10);
     		executor.setQueueCapacity(10);
     		executor.initialize();
     		return executor;
     	}
    
     }
  2. 在定时任务上加上 @Async 注解。

    @Scheduled(fixedDelay = 10)
     @Async
     public void p1(){
     	System.out.println(Thread.currentThread().getName() + "  p1");
     }
相关文章
相关标签/搜索