SpringBoot集成quartz创建定时任务

实现动态增删启停任务

1.在pom.xml中添加依赖

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

2.创建SchedulerListener类

package com.example.demo.config;

import com.example.demo.component.TaskManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class SchedulerListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    public TaskManager taskManager;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            taskManager.executeTasks();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        return schedulerFactoryBean;
    }

}

3.创建TaskManager类

package com.example.demo.component;

import com.example.demo.job.ScheduledJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 定时任务管理者
 */
@Component
public class TaskManager {

    /**
     * 存放所有定时任务
     */
    public static final List<ScheduledJob> JOB_LIST = new ArrayList<>();

    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    /**
     * 执行所有定时任务
     */
    public void executeTasks(){

        if(!CollectionUtils.isEmpty(JOB_LIST)){
            for (ScheduledJob job : JOB_LIST) {
                try {
                    //跑起来
                    job.startJob(schedulerFactoryBean.getScheduler());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }

}

4.创建ScheduledJob 类,所有需要运行的任务继承此抽象类即可

package com.example.demo.job;

import com.example.demo.component.TaskManager;
import org.quartz.*;
import javax.annotation.PostConstruct;

public  abstract class ScheduledJob implements Job {


    @PostConstruct
    public void init(){
        TaskManager.JOB_LIST.add(this);
    }

    /**
     * cron表达式在线生成 http://cron.qqe2.com/
     *
     * @return
     */
    public abstract String getCron();

    /**
     *
     * @param scheduler
     * 0/5 * * * * ?
     * @throws SchedulerException
     */
    public void startJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(this.getClass())
                .withIdentity(this.getClass().getName() + "-job", "group1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(getCron());
        CronTrigger cronTrigger = getCronTrigger(scheduleBuilder);
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }

    /**
     * 若要自定义触发器,请在子类重写此方法
     * @return
     */
    protected CronTrigger getCronTrigger(CronScheduleBuilder scheduleBuilder){
        return TriggerBuilder.newTrigger().withIdentity(this.getClass().getName() + "-trigger", "group1")
                .withSchedule(scheduleBuilder).build();

    }


}

5.具体job类 继承ScheduledJob,实现getCron()方法,execute()方法即可

package com.example.demo.component;

import com.example.demo.job.ScheduledJob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

@Component
public class Job2 extends ScheduledJob {


    /**
     * 从0秒开始,每1分钟跑一次
     *
     * @return
     */
    @Override
    public String getCron() {
        return "0 */1 * * * ?";
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("job2 is running.............."+new Date());
    }
}

5.1如果具体的Job类中调用service层,直接使用@Autowired会报错,可以使用ApplicationContext.getBean方法注入

package com.example.demo.component;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    public static <T> T getBean(Class<T> cls) {
        return applicationContext.getBean(cls);
    }
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<?> getType(String name) {
        return applicationContext.getType(name);
    }

}

Job类

package com.example.demo.component;

import com.example.demo.job.ScheduledJob;
import com.example.demo.service.HelloService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Job1 extends ScheduledJob {
    @Autowired
    private HelloService helloService;

    /**
     * 从0秒开始,每1分钟跑一次
     *
     * @return
     */
    @Override
    public String getCron() {
        return "0 */1 * * * ?";
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        helloService = SpringContextUtils.getBean(HelloService.class);
        helloService.SayHello();
        System.out.println("job1 is running.............."+new Date());
    }


}

6.运行结果

代码下载地址:https://github.com/anny130688/quartz.git

参考链接:

https://blog.csdn.net/qq_29145405/article/details/81843123

https://blog.csdn.net/shenjuntao520/article/details/100150821

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值