码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-08-23 13:24:10      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:start   编写   bsp   int   rabl   inter   return   cut   ram   

一、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实现多任务定时执行

标签:start   编写   bsp   int   rabl   inter   return   cut   ram   

原文地址:https://www.cnblogs.com/ring2/p/11399295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!