quartz实现间隔定时任务和指定时间的定时任务

本文档展示了如何使用Spring配置Quartz进行定时任务的设置,包括创建JobFactory和SchedulerFactoryBean,以及定义定时任务类DoorFaceDownJob,用于在项目启动时执行人脸下发任务,并支持按分钟间隔或指定日期触发任务。此外,还提供了任务的删除功能。
摘要由CSDN通过智能技术生成

0.配置类

package com.zjy.iot.smart.fully.config;

import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.io.IOException;

@Configuration
public class QuartzConfig {
    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setAutoStartup(true);
        factory.setJobFactory(jobFactory);
        return factory;
    }

    public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

        private transient AutowireCapableBeanFactory beanFactory;

        @Override
        public void setApplicationContext(final ApplicationContext context) {
            beanFactory = context.getAutowireCapableBeanFactory();
        }

        @Override
        protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
            final Object job = super.createJobInstance(bundle);
            beanFactory.autowireBean(job);
            return job;
        }
    }
}

1.定时任务类

package com.zjy.iot.smart.fully.job;

import com.zjy.iot.smart.fully.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class DoorFaceDownJob implements Job {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @PostConstruct
    public void initJob() {
        //项目启动时 查询当前未下发的数据
        log.info("项目启动执行人脸下发定时任务------>");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse("2021-4-21 14:21:20");
            addJobByDate(date, 123);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增任务 分钟
     *
     * @param interval 间隔分钟
     * @param tenantId 租户id
     */
    public void addJobByMinutes(Integer interval, Integer tenantId) {
        try {
            String cron = "0 0/" + interval + " * * * ? ";
            String task = Constants.FACE_DOWN_TASK + tenantId;
            String group = Constants.FACE_DOWN_TASK_GROUP;
            Scheduler scheduler = null;
            if (schedulerFactoryBean == null) {
                scheduler = new StdSchedulerFactory().getScheduler();
            } else {
                scheduler = schedulerFactoryBean.getScheduler();
            }
            if (scheduler.checkExists(JobKey.jobKey(task, group))) {
                log.info("该任务已存在->task:{},group:{}", task, group);
                return;
            }
            JobDataMap map = new JobDataMap();
            map.put("tenantId", tenantId);
            JobDetail jobDetail = JobBuilder.newJob(DoorFaceDownJob.class).setJobData(map)
                    .withIdentity(task, group)
                    .build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .forJob(jobDetail)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionFireAndProceed())
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
            log.info("addJob->tenantId:{},cron:{}", tenantId, cron);
        } catch (Exception e) {
            log.info("新增任务失败!");
        }
    }

    /**
     * 指定时间的定时任务
     * @param targetDate 日期
     * @param dataId 数据
     */
    public void addJobByDate(Date targetDate, Integer dataId) {
        try {
            String task = Constants.FACE_DOWN_TASK + dataId;
            String group = Constants.FACE_DOWN_TASK_GROUP;
            Scheduler scheduler = null;
            if (schedulerFactoryBean == null) {
                scheduler = new StdSchedulerFactory().getScheduler();
            } else {
                scheduler = schedulerFactoryBean.getScheduler();
            }
            if (scheduler.checkExists(JobKey.jobKey(task, group))) {
                log.info("该任务已存在->task:{},group:{}", task, group);
                return;
            }
            JobDataMap map = new JobDataMap();
            map.put("dataId", dataId);
            JobDetail jobDetail = JobBuilder.newJob(DoorFaceDownJob.class).setJobData(map)
                    .withIdentity(task, group)
                    .build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .forJob(jobDetail)
                    .startAt(targetDate).build();
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
            log.info("新增任务成功->dataId:{}", dataId);
        } catch (Exception e) {
            log.info("新增任务失败!");
        }
    }


    /**
     * 删除任务
     *
     * @param taskName  任务名
     * @param taskGroup 分组名
     * @throws SchedulerException exception
     */
    public void deleteJob(String taskName, String taskGroup) throws SchedulerException {
        //判断任务存在、存在返回成功
        Scheduler scheduler = null;
        if (schedulerFactoryBean == null) {
            scheduler = new StdSchedulerFactory().getScheduler();
        } else {
            scheduler = schedulerFactoryBean.getScheduler();
        }
        JobKey jobKey = JobKey.jobKey(taskName, taskGroup);
        //判断任务已被删除
        if (!scheduler.checkExists(jobKey)) {
            log.info("任务已删除或不存在");
        }
        boolean deleteJob = scheduler.deleteJob(jobKey);
        log.info("deleteJob->deleteJob:{}", deleteJob);
    }

    /**
     * 执行方法
     *
     * @param jobExecutionContext jobExecutionContext
     * @throws JobExecutionException JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        int dataId = jobExecutionContext.getJobDetail().getJobDataMap().getInt("dataId");
        log.info("开始执行删除重试任务->dataId:{}", dataId);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值