从零开始学springboot

32.从零开始学springboot-一篇搞定Schedule定

2019-08-01  本文已影响184人  码哥说

前言

实际开发中,经常会碰到“定期定时去做一些重复操作”的需求,这个时候,定时任务显得是那么的方便.本章,我们来讲讲SpringBoot的定时任务如何使用.

分类

使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式

基于注解(单线程)

基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。
什么意思呢?
意思就是假设基于注解注册了两个定时任务,我们叫做task1和task2
假设task1每5s执行一次并延时10s在执行下一次.
假设task2每5s执行一次.

@Scheduled默认为单线程的执行机制会导致如下情况:
task2在task1执行后才执行的(也就是task2实际上10s后才开始执行)

@Scheduled支持多种注解(参数),我们接下来一一演示

占位符

占位符概念

这边补上一个占位符的概念,因为后面会用到.

假设你将定时任务的时间周期写在了配置文件里,那么此时,你编写定时任务时如何自动识别呢?
这就使用到了占位符.

占位符的使用

yml配置文件中有配置:

time:
  cron: */5 * * * * *
  interval: 5

此时使用注解定时任务应该使用占位符

    @Scheduled(cron="${time.cron}")
    void testCron1() {
        System.out.println("占位符演示1" + System.currentTimeMillis());
    }

    @Scheduled(cron="*/${time.interval} * * * * *")
    void testCron2() {
        System.out.println("占位符演示2" + System.currentTimeMillis());
    }

八大参数-cron表达式(支持占位符)

语法

cron表达式语法
[秒] [分] [小时] [日] [月] [周] [年]
注:[年]不是必须的域,可以省略[年],则一共6个域

cron.png

通配符

关于各个通配符的意义如下:

例如:在分的字段上设置 *,表示每一分钟都会触发。
使用的场景为不需要关心当前设置这个字段的值。例如:要在每月
的10号触发一个操作,但不关心是周几,所以需要周位置的那个
字段设置为”?” 具体设置为 0 0 0 10 * ?
例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。
例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触
发
如在秒上面设置”5/15” 表示从5秒开始,每增15秒触(5,20,35,50)。 
在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。
在日字段设置上,表示当月的最后一天(依据当前月份,如果是二
月还会依据是否是润年[leap]), 在周字段上表示星期六,相当
于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。
例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”
例如在日字段上置”15W”,表示离每月15号最近的那个工作日触
发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号
是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周
一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每
月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周
一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。
例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指
定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父
亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在
日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段
的设置,若使用英文字母是不区分大小写的,即MON与mon相
同。

通配符实例

为了帮助大家理解,我们在举几个例子:

cron定时任务实例

package com.mrcoder.sbschedule.job;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Component
@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   //2.开启定时任务
public class StaticSchedule {
    //3.添加定时任务
    //基于注解@Scheduled默认为单线程
    //开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。
    //这边定时任务1延时10s来演示这个单线程的问题
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());

        try {
            Thread.sleep(1000 * 10);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            System.err.println(ex);
        }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks2() {
        System.err.println("执行静态定时任务(单线程)2: " + LocalDateTime.now().toLocalTime());
    }
}

八大参数-ZONE

时区,接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。

使用实例

    @Scheduled(cron = "0/5 * * * * ?", zone = "")
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

八大参数-fixedDelay

fixedDelay用于上一次执行完毕时间点之后多长时间再执行

使用实例

    //上一次执行完毕时间点之后5秒再执行
    @Scheduled(fixedDelay = 5000) 
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

八大参数-fixedDelayString(支持占位符)

与fixedDelay相同,只是使用字符串的形式。唯一不同的是支持占位符。

使用实例

    //上一次执行完毕时间点之后5秒再执行
    @Scheduled(fixedDelayString = "5000")
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

八大参数-fixedRate

上一次开始执行时间点之后多长时间再执行

使用实例

    //上一次开始执行时间点之后5秒再执行
    @Scheduled(fixedRate = 5000) 
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

八大参数-fixedRateString(支持占位符)

与fixedRate相同,只是使用字符串的形式。唯一不同的是支持占位符。

使用实例

    //上一次开始执行时间点之后5秒再执行
    @Scheduled(fixedRateString = "5000") 
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

八大参数-initialDelay

第一次延迟多长时间后再执行

使用实例

    //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
    @Scheduled(initialDelay = 1000, fixedRate = 5000) 
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

八大参数-initialDelayString(支持占位符)

与initialDelay相同,只是使用字符串的形式。唯一不同的是支持占位符。

使用实例

    //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
    @Scheduled(initialDelayString = "1000", fixedRate = 5000) 
    private void configureTasks() {
        System.err.println("执行静态定时任务(单线程)1: " + LocalDateTime.now().toLocalTime());
    }

基于注解(多线程)

这边主要使用注解@EnableAsync开启多线程支持
使用注解@Async来表明定义一个异步的线程任务

案例

package com.mrcoder.sbschedule.job;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Component
@EnableScheduling //1.开启定时任务
@EnableAsync      //2.开启多线程,开启后多个定时任务不会互相影响

public class ThreadSchedule {
    @Async
    @Scheduled(fixedDelay = 1000) //间隔1秒
    public void first() {
        System.err.println("执行定时任务(多线程)1 : " + LocalDateTime.now().toLocalTime() + "线程 : " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000 * 10);
        } catch (InterruptedException ex) {

            Thread.currentThread().interrupt();
            System.err.println(ex);
        }
    }

    @Async
    @Scheduled(fixedDelay = 2000)
    public void second() {
        System.err.println("执行定时任务(多线程)2 : " + LocalDateTime.now().toLocalTime() + "线程 : " + Thread.currentThread().getName());
    }
}

基于接口SchedulingConfigurer(单/多线程)

上一小结介绍了基于注解@Scheduled的定时任务,可以看到,很方便.但是有个致命的缺点,
就是当需要临时调整定时任务执行周期时,必须要实时的重启应用才能生效.
那么能不能不重启应用就能“动态”调整定时任务的执行周期呢?

下面我们介绍基于接口SchedulingConfigurer的定时任务实现方式.

需要说明的是,SchedulingConfigurer默认使用的也是单线程的方式,如果需要配置多线程,则需要指定 PoolSize,加入如下代码即可:

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        //10个线程
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

案例

定时任务周期库

创建一张表用来存储定时任务的执行周期,后续调整周期时直接修改对应的记录即可

DROP DATABASE
IF
    EXISTS `demo`;
CREATE DATABASE `demo`;
USE `demo`;
DROP TABLE
IF
    EXISTS `crontab`;
CREATE TABLE `crontab` ( `cron_id` VARCHAR ( 30 ) NOT NULL PRIMARY KEY, `cron` VARCHAR ( 30 ) NOT NULL );
INSERT INTO `crontab`
VALUES
    ( '1', '0/10 * * * * ?' );

配置yml

spring:
  datasource:
    url: jdbc:mysql://127.0.01:3306/demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

实现SchedulingConfigurer接口

package com.mrcoder.sbschedule.job;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;


@Component
//1.主要用于标记配置类,兼备Component的效果。
@Configuration
//2.开启定时任务
@EnableScheduling
public class DynamicSchedule implements SchedulingConfigurer {
    @Mapper
    public interface CronMapper {
        @Select("select cron from crontab limit 1")
        public String getCron();
    }

    //注入mapper
    @Autowired
    @SuppressWarnings("all")
    CronMapper cronMapper;

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        //多线程支持,线程池创建10个线程
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
        

        //定时任务1: 每1s执行一次(每执行一次睡眠10s)
        taskRegistrar.addFixedRateTask(
                new Runnable() {
                    //添加任务内容
                    @Override
                    public void run() {
                        System.err.println("执行动态定时任务1: " + LocalDateTime.now().toLocalTime());
                        //为了验证多线程不阻塞,这边睡眠 10s
                        try {
                            Thread.sleep(1000 * 10);
                        } catch (InterruptedException ex) {
                            Thread.currentThread().interrupt();
                            System.err.println(ex);
                        }
                    }
                }
                , 1000);

        //定时任务2: 读取mysql中的执行cron公式
        TriggerTask triggrtTask = new TriggerTask(
                //1.添加任务内容(Runnable),这边使用"拉姆达表达式"
                () -> System.err.println("执行动态定时任务2: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
        taskRegistrar.addTriggerTask(triggrtTask);
    }
}

案例代码

https://github.com/MrCoderStack/SpringBootDemo/tree/master/sb-schedule

请关注我的订阅号

订阅号.png
上一篇下一篇

猜你喜欢

热点阅读