spring 定时调度

spring task

在spring 3.0+,集成了spring task 对定时任务的调度提供支持,基于注解的方式,但是对于任务队列和线程池管控较弱
对于启动类,需要使用@EnableScheduling 注解开启定时任务

package com.zyd;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
/**
 * 开启定时任务注解
 */
@EnableScheduling
public class StudyCloudApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudyCloudApplication.class, args);
    }

}

实现类

package com.zyd.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;

@Component
public class SpringTask {

    @Scheduled(cron = "0/2 * * * * ?")
    public void job(){
        System.out.println("定时任务:"+ LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
}

corn 从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份(可省)
含义

位置 时间域名 允许值 允许的特殊字符
1 0-59 - * /
2 分钟 0-59 - * /
3 小时 0-23 - * /
4 1-31 - * / L W C
5 1-12 - * /
6 星期 1-7 - * ? / L C #
7 年(可选) 1970-2099 - * /

cron 表达式的时间字段除允许设置数值外,还可使用一些特殊的字符,提供列表、范围、通配符等功能:

  • 星号*:可用在所有字段中,表示对应时间域的每一个时刻,例如,*在分钟字段时,表示“每分钟”;

  • 问号?:该字符只在日期和星期字段中使用,它通常指定为“无意义的值”,相当于占位符;

  • 减号-:表达一个范围,如在小时字段中使用“10-12”,则表示从 10 到 12 点,即 10,11,12;

  • 逗号,:表达一个列表值,如在星期字段中使用“MON,WED,FRI”,则表示星期一,星期三和星期五; 斜杠/:x/y

  • / 表达一个等步长序列,x 为起始值,y 为增量步长值。如在分钟字段中使用 0/15,则表示为 0,15,30 和 45 秒,而 5/15 在分钟字段中表示 5,20,35,50,你也可以使用*/y,它等同于 0/y;

  • L:该字符只在日期和星期字段中使用,代表“Last”的意思,但它在两个字段中意思不同。L 在日期字段中,表示这个月份的最后一天,如一月的 31 号,非闰年二月的 28 号;如果 L 用在星期中,则表示星期六,等同于 7。但是,如果 L 出现在星期字段里,而且在前面有一个数值 X,则表示“这个月的最后 X 天”,例如,6L 表示该月的最后星期五;

  • W:该字符只能出现在日期字段里,是对前导日期的修饰,表示离该日期最近的工作日。例如 15W表示离该月 15 号最近的工作日,如果该月 15 号是星期六,则匹配 14 号星期五;如果 15 日是星期日,则匹配 16 号星期一;如果 15 号是星期二,那结果就是 15 号星期二。但必须注意关联的匹配日期不能够跨月,如你指定 1W,如果 1 号是星期六,结果匹配的是 3 号星期一,而非上个月最后的那天。W 字符串只能指定单一日期,而不能指定日期范围;

  • LW 组合:在日期字段可以组合使用 LW,它的意思是当月的最后一个工作日;

  • 井号#:该字符只能在星期字段中使用,表示当月某个工作日。如 6#3 表示当月的第三个星期五(6表示星期五,#3 表示当前的第三个),而 4#5 表示当月的第五个星期三,假设当月没有第五个星期三,忽略不触发;

  • C:该字符只在日期和星期字段中使用,代表“Calendar”的意思。它的意思是计划所关联的日期,如果日期没有被关联,则相当于日历中所有日期。例如 5C 在日期字段中就相当于日历 5 日以后的第一天。1C 在星期字段中相当于星期日后的第一天。
      cron 表达式对特殊字符的大小写不敏感,对代表星期的缩写英文大小写也不敏感。

例子:

@Scheduled(cron = “0 0 1 1 1 ?”) // 每年一月的一号的 1:00:00 执行一次
@Scheduled(cron = “0 0 1 1 1,6 ?”) // 每年一月和六月的一号的 1:00:00 执行一次
@Scheduled(cron = “0 0 1 1 1,4,7,10 ?”) // 每年每个季度的第一个月的一号的 1:00:00 执行一次
@Scheduled(cron = “0 0 1 1 * ?”) // 每年每月一号 1:00:00 执行一次
@Scheduled(cron=“0 0 1 * * *”) // 每年每天凌晨 1 点执行一次

Quartz

基于Java编写的开源作业调度框架,允许开发人员根据时间间隔来调度作业,实现了作业与触发器多对多的关系,还可以将多个作业与不同的触发器并联

相关组件

scheduler

调度器,进行任务调度,Quarz的主控制室

Job

业务Job,定时任务的具体执行业务,调度器调用此接口的execute方法完成定时任务

JobDetail

来定义业务 Job 的实例

JobBuilder

Job构建器,定义和创建JobDetail

TriggerBuilder

触发器构建器,用来定义或创建触发器的实例

依赖

<dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.1</version>
</dependency>

样例

job类

package com.zyd.task;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class QuartzDemo implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("调度器会调用此接口的 execute 方法完成我们的定时业务"+System.currentTimeMillis());
    }
}

启动类

package com.zyd.task;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzTest {
    public static void main(String[] args) {
        //1. 创建Job对象
        JobDetail jobBuild = JobBuilder.newJob(QuartzDemo.class).build();
        // 2. Cron Trigger触发器,按cron表达式定义触发时间
        Trigger triggerBuilder = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")).build();
        //3. 创建Scheduler对象
        Scheduler scheduler = null;
        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();

            //4. 绑定
            scheduler.scheduleJob(jobBuild, triggerBuilder);
            //5. 启动
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

集成spring

依赖

	 <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.1</version>
        </dependency>

        <!-- quartz 使用了该jar包PlatformTransactionManager类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <!-- 该依赖里面有spring对schedule的支持 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

job类

简单job

package com.zyd.task;

import com.zyd.service.StudentService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class SpringQuartzJob  extends QuartzJobBean {
    
    @Autowired
    StudentService studentService;
    
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("定时任务执行:"+System.currentTimeMillis());
        studentService.printName();
    }
}

定时job

业务层

package com.zyd.service;

public interface StudentService {
    void printName();
}

package com.zyd.service.impl;

import com.zyd.service.StudentService;

public class StudentServiceImpl implements StudentService {

    @Override
    public void printName() {
        System.out.println("疫情结束,该去上学了!");
    }
}

调度配置中心

  1. 简单时间调度
package com.zyd.config;

import com.zyd.task.SpringQuartzJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    /**
     * 使用JobDetail 封装job
     *
     * @return JobDetail
     */
    @Bean
    public JobDetail simpleJob() {
        return JobBuilder.newJob(SpringQuartzJob.class)
                .withIdentity("simpleJobDetail") //定义name
                .storeDurably() // 有触发器关联就会调用,没有不会调用
                .build();
    }

    /**
     * 把 JobDetail 注册到 Trigger 触发器
     *
     * @return Trigger
     */
    @Bean
    public Trigger simJobTrigger() {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()  //简单的trigger 触发器
                .withIntervalInSeconds(2)  //两秒执行一次
                .repeatForever();//永远运行

        return TriggerBuilder.newTrigger()
                .forJob(simpleJob()) //JobDetail
                .withIdentity("simpleJobTrigger")   //定义name
                .startNow() //一旦加入schedule 立即生效
                .withSchedule(scheduleBuilder)  //SimpleScheduleBuilder
                .build();
    }
}

  1. cron 表达式调度
package com.zyd.config;

import com.zyd.task.SpringQuartzJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    /**
     * 使用JobDetail 封装job
     *
     * @return JobDetail
     */
    @Bean
    public JobDetail simpleJob() {
        return JobBuilder.newJob(SpringQuartzJob.class)
                .withIdentity("simpleJobDetail") //定义name
                .storeDurably() // 有触发器关联就会调用,没有不会调用
                .build();
    }

    /**
     * 把 JobDetail 注册到 Trigger 触发器
     *
     * @return Trigger
     */
    @Bean
    public Trigger simJobTrigger() {
//        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder
//                .simpleSchedule()  //简单的trigger 触发器
//                .withIntervalInSeconds(2)  //两秒执行一次
//                .repeatForever();//永远运行

        // Cron Trigger 触发器:按照 cron 的表达式来给定触发的时间
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder
                .cronSchedule("0/3 * * * * ?");

        return TriggerBuilder.newTrigger()
                .forJob(simpleJob()) //JobDetail
                .withIdentity("simpleJobTrigger")   //定义name
                .startNow() //一旦加入schedule 立即生效
                .withSchedule(cronScheduleBuilder)  //SimpleScheduleBuilder
                .build();
    }
}

发布了483 篇原创文章 · 获赞 62 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/wwwzydcom/article/details/105231281