SpringBoot2.x整合quartz实现多任务定时执行

Posted ring2

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2.x整合quartz实现多任务定时执行相关的知识,希望对你有一定的参考价值。

一、pom文件中导入相关依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

二、分别编写任务代码类

/**
 * 任务一
 */
public class MyQuartzJob extends QuartzJobBean 

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException 
        System.out.println("talk is cheap.");
    
/**
 * 任务二
 */
public class MyQuartzJob1 extends QuartzJobBean 

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException 
        System.out.println("show me the code");
    

三、分别编写相关的scheduler类(也可以写在一个类里)

/**
 * Scheduler来调度Trigger和JobDetil
 * JobDetail来实例化Job类并可以传值
 */
@Configuration
public class MyScheduler 

    @Bean(name = "JobDetail")
    public JobDetail simpleJobDetail()

        JobDetail jobDetail = JobBuilder.newJob(MyQuartzJob.class).withIdentity("eclipse")
                .usingJobData("key","value").storeDurably().build();
        return jobDetail;
    

    @Bean(name = "trigger")
    public Trigger simpleJobTrigger()

        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(4).repeatForever();

        return TriggerBuilder.newTrigger().forJob(simpleJobDetail())
                .withIdentity("sampleTrigger").withSchedule(scheduleBuilder).build();
    
@Configuration
public class MyScheduler1 

    @Bean(name = "JobDetail1")
    public JobDetail simpleJobDetail1()

        JobDetail jobDetail = JobBuilder.newJob(MyQuartzJob1.class).withIdentity("eclipse1")
                .usingJobData("key","value").storeDurably().build();
        return jobDetail;
    

    @Bean(name = "trigger1")
    public Trigger simpleJobTrigger1()

        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(6).repeatForever();

        return TriggerBuilder.newTrigger().forJob(simpleJobDetail1())
                .withIdentity("sampleTrigger1").withSchedule(scheduleBuilder).build();
    

四、启动springboot即可查看任务执行情况

  具体的执行时间可以自己设置:这里分别是4秒和6秒:

技术图片

 

以上是关于SpringBoot2.x整合quartz实现多任务定时执行的主要内容,如果未能解决你的问题,请参考以下文章

springboot2.x整合quartz2.x.md

SpringBoot之整合Quartz调度框架-基于Spring Boot2.0.2版本

SpringBoot之整合Quartz调度框架-基于Spring Boot2.0.2版本

SpringBoot2.x整合WebSoket

springboot2.x版本整合redis(单机/集群)(使用lettuce)

SpringBoot整合Thymeleaf-基于SpringBoot2.X版本