Quartz定时任务项目中的应用

时间:2022-02-16 07:46:15
  1. 添加quartz依赖 pom.xm

    <!-- 添加Quartz支持 -->
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.2.1</version>
    </dependency>
  2. spring配置文件之quartz-context.xml,将此文件包含到spring的主配置文件里
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <bean id="stdSchedulerFactory" class="org.quartz.impl.StdSchedulerFactory"/>

</beans>
  1. Domain:定时任务的规则实体

    @Entity
    @Table(name = "t_task")
    public class Task{
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY) // MYSQL时可以这样使用自增
        @Column(name = "PK")
        private Integer id;
    
        // 探测时长
        @Column(name = "DETECTION_TIME")
        private Integer detectionTime;// 探测时长
    
        @Column(name = "detection_time_unit")
        private Integer detectionTimeUnit;//探测时长单位
    
        @Column(name = "DETECTION_Date")
        private Date detectionDate;// 探测时长时间的转换
    
        @Column(name = "task_company")
        private Integer company;//探测周期
    
        @Column(name = "task_company_format")
        private String companyFormat;//探测周期转换
    
        @Column(name = "company_unit")
        private Integer companyUnit;//探测周期单位
        //省略getter好setter方法
    }
  2. Controller:控制器

    package com.cnitsec.mirana.task.quartz.controller;
    
    import com.cnitsec.mirana.task.quartz.service.JobService;
    import org.quartz.Job;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /** * 类的注释 * * @Package com.cnitsec.mirana.task.quartz.controller * @ClassName JobController * @Description 定时任务控制器 * @Author * @Date 2018-05-31 10:47 */
    
    @RestController
    @RequestMapping("/job")
    public class JobController {
    
    
        @Autowired
        private JobService jobService;
    
        @RequestMapping("/quartzJob/{taskId}/{isQuartz}")
        public boolean quartzJob(@PathVariable String taskId, @PathVariable boolean isQuartz) {
            return jobService.quartzJob(taskId, isQuartz);
        }
    }
    
  3. Service:接口

    package com.cnitsec.mirana.task.quartz.service;
    
    /** * 接口注释 * * @Package com.cnitsec.mirana.task.quartz.service * @ClassName JobService * @Description 定时任务的接口 * @Author * @Date 2018-05-31 10:48 */
    
    public interface JobService {
    
        boolean quartzJob(String taskId,boolean isQuartz);
    }
    
  4. ServiceImpl:接口实现类

    package com.cnitsec.mirana.task.quartz.service.impl;
    
    import com.cnitsec.mirana.task.domain.ConfigTask;
    import com.cnitsec.mirana.task.quartz.HelloJob;
    import com.cnitsec.mirana.task.quartz.job.TaskJob;
    import com.cnitsec.mirana.task.quartz.service.JobService;
    import com.cnitsec.mirana.task.service.ConfigTaskService;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Date;
    
    import static org.quartz.JobBuilder.newJob;
    import static org.quartz.TriggerBuilder.newTrigger;
    
    /** * 类的注释 * * @Package com.cnitsec.mirana.task.quartz.service.impl * @ClassName JobServiceImpl * @Description 定时任务实现类 * @Author liyuzhi * @Date 2018-05-31 10:49 */
    @Service
    public class JobServiceImpl implements JobService {
    
        private final Logger logger = LoggerFactory.getLogger(HelloJob.class);
    
        @Autowired
        private StdSchedulerFactory stdSchedulerFactory;
    
        @Autowired
        private TaskService taskService;
    
    
        /** * 方法的注释 * * @return boolean 返货是否开启或者停止的结果状态 * @description 开启或者停止job工作 * @methodName quartzJob * @Param: taskId 前端传过来的任务Id * @Param: isQuartz 1.true为运行开启job 2.false 为停止job * @author liyuzhi * @createTime 2018-05-31 18:53 * @version v1.0 */
        @Override
        public boolean quartzJob(String taskId, boolean isQuartz) {
            try {
                Scheduler scheduler = getScheduler();
                if (isQuartz) {
                    if (exists(taskId, scheduler)) {//开启job之前先,判断Job是否存在,如果存在直接返回
                        return false;
                    }
                    startJob(taskId, scheduler);//开启job
                } else {
                    if (notExists(taskId, scheduler)) {//停止job的操作之前先,判断Job是否存在,如果不存在直接返货false,
                        return false;
                    }
                    stopJob(taskId, scheduler);//停止job
                }
                setQuartz(taskId, isQuartz);
                return true;
            } catch (SchedulerException e) {
                e.printStackTrace();
                return false;
            }
        }
    
        //停止job,
        private void stopJob(String taskId, Scheduler scheduler) throws SchedulerException {
            TriggerKey triggerKey = TriggerKey.triggerKey(taskId, taskId);
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(JobKey.jobKey(taskId, taskId));
        }
    
        //开启job
        private void startJob(String taskId, Scheduler scheduler) throws SchedulerException {
            JobDetail jobDetail = newJob(TaskJob.class).withIdentity(taskId, taskId).build();//设置job
            CronTrigger trigger = newTrigger().withIdentity(taskId, taskId).
                    withSchedule(CronScheduleBuilder.cronSchedule(getTriggerTime(taskId))).endAt(getDetectionDate(taskId)).build();//设置job触发器
            scheduler.scheduleJob(jobDetail, trigger);
            startJob(scheduler);//开启定时任务,如果任务开启则直接返回
        }
    
        //获取运行的规则
        private String getTriggerTime(String taskId) {
            //下边的方法是自己具体的增删改查,需要自己去实现
            return taskService.findOne(Integer.parseInt(taskId)).getCompanyFormat();
        }
    
    
        //获取运行的延迟时间
        private Date getDetectionDate(String taskId) {
            //下边的方法是自己具体的增删改查,需要自己去实现
            return configTaskService.findOne(Integer.parseInt(taskId)).getDetectionDate();
        }
    
    
        //保存quartz的状态到数据库
        private void setQuartz(String taskId, boolean isQuartz) {
            Task task = taskService.findOne(Integer.parseInt(taskId));
            task.setQuartz(isQuartz);
            configTaskService.saveTask(task);
        }
    
        /** * 方法的注释 * * @return void * @description 如果定时任务没有开启。则调用此方法开启定时任务 * @methodName startJob * @Param: scheduler * @author * @createTime 2018-05-31 13:54 * @version v1.0 */
        private void startJob(Scheduler scheduler) throws SchedulerException {
            boolean started = scheduler.isStarted();
            if (!started) {
                scheduler.start();
            }
        }
    
    
        /** * 方法的注释 * * @return boolean * @description 判断Job是否存在 * @methodName exists * @Param: taskId 任务Id * @Param: scheduler * @author * @createTime 2018-05-31 13:53 * @version v1.0 */
        private boolean exists(String taskId, Scheduler scheduler) throws SchedulerException {
            boolean exists = scheduler.checkExists(JobKey.jobKey(taskId, taskId));
            if (exists) {
                logger.info("该Job已经存在了-----------------------------------------------");
                return true;
            }
            return false;
        }
    
    
        /** * 方法的注释 * * @return boolean * @description 当执行停止一个任务的时候先判断该任务是否存在,存在才可以执行停止一个任务。 * @methodName notExists * @Param: taskId * @Param: scheduler * @author * @createTime 2018-05-31 13:55 * @version v1.0 */
        private boolean notExists(String taskId, Scheduler scheduler) throws SchedulerException {
            boolean exists = scheduler.checkExists(JobKey.jobKey(taskId, taskId));
            if (!exists) {
                logger.info("该Job不存在-----------------------------------------------");
                return true;
            }
            return false;
        }
    
        private Scheduler getScheduler() throws SchedulerException {
            return stdSchedulerFactory.getScheduler();
        }
    }
    
  5. Job:具体的定时任务

    package com.cnitsec.mirana.task.quartz.job;
    
    import com.cnitsec.mirana.task.quartz.HelloJob;
    import com.cnitsec.mirana.task.service.ConfigTaskService;
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    
    /** * 类的注释 * * @Package com.cnitsec.mirana.task.quartz.job * @ClassName TaskJob * @Description 定时任务的JoB * @Author * @Date 2018-05-31 10:32 */
    
    public class TaskJob implements Job {
        private final Logger logger = LoggerFactory.getLogger(HelloJob.class);
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    
            logger.info(jobExecutionContext.getJobDetail().getKey().getName() + "成功执行定时任务-------------------------------------------------");
        }
    }