spring boot 实现任务调度quartz

结合spring boot 实现quartz任务调度

  1. 首先在pom.xml中加入
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-quartz -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

  1. 实现Job接口
package com.cm.project.quartzs;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;


@Slf4j
@Component
public class ScheduleQuartzJob implements Job {

    @Autowired
    private TaskIntervalQuartz taskIntervalQuartz;

    private void before() {
        System.out.println("-----开始任务执行-----");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        before();
        
        JobKey jobKey = jobExecutionContext.getJobDetail().getKey();
        String jobName = jobKey.getName();
        // TODO 具体业务实现
        
        after();
    }

    private void after() {
        System.out.println("-----结束任务执行-----");
    }
}

  1. 具体实现调度方法
package com.cm.bmpbroadcast.quartzs;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TaskIntervalQuartz {

    private static String JOB_GROUP_NAME = "JOB_CLOUD_RADIOT";

    @Autowired
    private Scheduler scheduler;

    /**
     * 添加定时任务
     *
     * @param jobName 任务名称
     * @param time    时间
     * @throws Exception
     */
    public void addJob(Scheduler scheduler, String jobName, String time) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(ScheduleQuartzJob.class).withIdentity(jobName, JOB_GROUP_NAME).build();
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, JOB_GROUP_NAME)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);

    }

    /**
     * 开启任务
     *
     * @param jobName 任务名称
     * @param time    时间
     */
    public void startJob(String jobName, String time) {
        try {
            addJob(scheduler, jobName, time);
            scheduler.start();
        } catch (SchedulerException e) {
            return;
        }
    }

    /**
     * 删除任务
     *
     * @param jobName 任务名称
     */
    public void deleteJob(String jobName) {
        try {
            JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测是否存在任务
     *
     * @param jobName
     * @return
     */
    public Boolean getJob(String jobName) {
        try {
            JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
            return scheduler.checkExists(jobKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 恢复某个任务
     *
     * @param jobName 任务名称
     */
    public void resumeJob(String jobName) {
        try {
            JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return;
            }
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            e.getUnderlyingException();
        }
    }
}

使用的是Cron表达式,所以, 需要拼接时间.
Cron表达式的规则:秒 分 时 日 月 周 年。除非有特定年,否则可以直接去掉。
Cron在线检查

在spring boot中可能会导致注入bean失败的情况,那么就需要手动注入

package com.cm.project.quartzs;

import org.quartz.Scheduler;
import org.quartz.spi.JobFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {
    private JobFactory jobFactory;

    public QuartzConfig(JobFactory jobFactory){
        this.jobFactory = jobFactory;
    }

    /**
     * 配置SchedulerFactoryBean
     * 将一个方法产生为Bean并交给Spring容器管理
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        // Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 设置自定义Job Factory,用于Spring管理Job bean
        factory.setJobFactory(jobFactory);
        return factory;
    }

    @Bean(name = "scheduler")
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }
}

package com.cm.project.quartzs;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

/**
 * 解决SpringBoot不能在Quartz中注入Bean的问题
 */
@Component
public class JobFactory extends AdaptableJobFactory {

    //将一个对象加入到SpringIOC容器中,并且完成对象注入
    @Autowired
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

    /**
     * 将实列化的任务对象手动加入到SpringIOC容器中,并且完成对象注入
     *
     * @param bundle
     * @return
     * @throws Exception
     */
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        Object object = super.createJobInstance(bundle);
        //将object添加到SpringIOC容器中,并完成对象的注入
        this.autowireCapableBeanFactory.autowireBean(object);
        return object;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一种简单而强大的方式来实现定时任务调度。下面是使用Spring Boot实现定时任务调度的步骤: 1. 添加依赖:在`pom.xml`文件添加Spring Boot的定时任务依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> ``` 2. 创建定时任务类:创建一个继承自`QuartzJobBean`的定时任务类,并实现`executeInternal`方法,该方法编写具体的定时任务逻辑。 ```java import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class MyJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // 定时任务逻辑 System.out.println("定时任务执行..."); } } ``` 3. 配置定时任务:在`application.properties`或`application.yml`文件配置定时任务的相关属性,例如触发时间、触发频率等。 ```yaml spring: quartz: job-store-type: memory properties: org: quartz: scheduler: instanceName: MyScheduler instanceId: AUTO job-details: my-job: cron: 0/5 * * * * ? job-class-name: com.example.MyJob ``` 4. 启动定时任务:在Spring Boot的启动类上添加`@EnableScheduling`注解,开启定时任务的自动配置。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 5. 运行定时任务:启动Spring Boot应用程序后,定时任务将按照配置的触发时间和频率执行。 以上就是使用Spring Boot实现定时任务调度的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值