• Quartz定时任务


    动态添加、修改和删除定时任务

    pom.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.1.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
            <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz</artifactId>
                <version>2.2.1</version>
            </dependency>
    
            <!-- Use MySQL Connector-J -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>
    

     动态添加、修改和删除定时任务管理类:

    package com.example.demo;
    
    import org.quartz.CronScheduleBuilder;
    import org.quartz.CronTrigger;
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.JobKey;
    import org.quartz.Scheduler;
    import org.quartz.SchedulerFactory;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.TriggerKey;
    import org.quartz.impl.StdSchedulerFactory;
    
    public class QuartzManager {
    
        private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    
        /**
         * @param jobName          任务名
         * @param jobGroupName     任务组名
         * @param triggerName      触发器名
         * @param triggerGroupName 触发器组名
         * @param jobClass         任务
         * @param cron             时间设置,参考quartz说明文档
         * @Description: 添加一个定时任务
         */
        public static void addJob(String jobName, String jobGroupName,
                                  String triggerName, String triggerGroupName, Class jobClass, String cron) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                // 任务名,任务组,任务执行类
                JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
    
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                CronTrigger trigger = (CronTrigger) triggerBuilder.build();
    
                // 调度容器设置JobDetail和Trigger
                sched.scheduleJob(jobDetail, trigger);
    
                // 启动
                if (!sched.isShutdown()) {
                    sched.start();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * @param jobName
         * @param jobGroupName
         * @param triggerName      触发器名
         * @param triggerGroupName 触发器组名
         * @param cron             时间设置,参考quartz说明文档
         * @Description: 修改一个任务的触发时间
         */
        public static void modifyJobTime(String jobName,
                                         String jobGroupName, String triggerName, String triggerGroupName, String cron) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
                CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
                if (trigger == null) {
                    return;
                }
    
                String oldTime = trigger.getCronExpression();
                if (!oldTime.equalsIgnoreCase(cron)) {
                    /** 方式一 :调用 rescheduleJob 开始 */
                    // 触发器
                    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                    // 触发器名,触发器组
                    triggerBuilder.withIdentity(triggerName, triggerGroupName);
                    triggerBuilder.startNow();
                    // 触发器时间设定
                    triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                    // 创建Trigger对象
                    trigger = (CronTrigger) triggerBuilder.build();
                    // 方式一 :修改一个任务的触发时间
                    sched.rescheduleJob(triggerKey, trigger);
                    /** 方式一 :调用 rescheduleJob 结束 */
    
                    /** 方式二:先删除,然后在创建一个新的Job  */
                    //JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                    //Class<? extends Job> jobClass = jobDetail.getJobClass();
                    //removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                    //addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);
                    /** 方式二 :先删除,然后在创建一个新的Job */
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * @param jobName
         * @param jobGroupName
         * @param triggerName
         * @param triggerGroupName
         * @Description: 移除一个任务
         */
        public static void removeJob(String jobName, String jobGroupName,
                                     String triggerName, String triggerGroupName) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
    
                TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
    
                sched.pauseTrigger(triggerKey);// 停止触发器
                sched.unscheduleJob(triggerKey);// 移除触发器
                sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * @Description:启动所有定时任务
         */
        public static void startJobs() {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                sched.start();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * @Description:关闭所有定时任务
         */
        public static void shutdownJobs() {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                if (!sched.isShutdown()) {
                    sched.shutdown();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    

     定时任务类:

    package com.example.demo;
    
    import java.util.Date;
    
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    
    public class MyJob implements Job {
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println(new Date() + ": ----------------------doing something...");
        }
    }
    

     测试类:

    package com.example.demo;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class DemoApplicationTests {
    
        public static String JOB_NAME = "动态任务调度";
        public static String TRIGGER_NAME = "动态任务触发器";
        public static String JOB_GROUP_NAME = "任务组名字";
        public static String TRIGGER_GROUP_NAME = "任务触发器组名字";
        
        @Test
        public void testJob() {
            try {
                System.out.println("【系统启动】开始(每1秒输出一次)...");
                QuartzManager.addJob(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME, MyJob.class, "0/1 * * * * ?");
    
                Thread.sleep(5000);
                System.out.println("【修改时间】开始(每5秒输出一次)...");
                QuartzManager.modifyJobTime(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME, "0/5 * * * * ?");
    
                Thread.sleep(60000);
                System.out.println("【移除定时】开始...");
                QuartzManager.removeJob(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME);
                System.out.println("【移除定时】成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

     持久化定时任务到数据库:

    创建MySQL存放任务的表:

    DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
    DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
    DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
    DROP TABLE IF EXISTS QRTZ_LOCKS;
    DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
    DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
    DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
    DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
    DROP TABLE IF EXISTS QRTZ_TRIGGERS;
    DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
    DROP TABLE IF EXISTS QRTZ_CALENDARS;
    
    
    CREATE TABLE QRTZ_JOB_DETAILS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        JOB_NAME  VARCHAR(200) NOT NULL,
        JOB_GROUP VARCHAR(200) NOT NULL,
        DESCRIPTION VARCHAR(250) NULL,
        JOB_CLASS_NAME   VARCHAR(250) NOT NULL,
        IS_DURABLE VARCHAR(1) NOT NULL,
        IS_NONCONCURRENT VARCHAR(1) NOT NULL,
        IS_UPDATE_DATA VARCHAR(1) NOT NULL,
        REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
        JOB_DATA BLOB NULL,
        PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
    );
    
    CREATE TABLE QRTZ_TRIGGERS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        TRIGGER_NAME VARCHAR(200) NOT NULL,
        TRIGGER_GROUP VARCHAR(200) NOT NULL,
        JOB_NAME  VARCHAR(200) NOT NULL,
        JOB_GROUP VARCHAR(200) NOT NULL,
        DESCRIPTION VARCHAR(250) NULL,
        NEXT_FIRE_TIME BIGINT(13) NULL,
        PREV_FIRE_TIME BIGINT(13) NULL,
        PRIORITY INTEGER NULL,
        TRIGGER_STATE VARCHAR(16) NOT NULL,
        TRIGGER_TYPE VARCHAR(8) NOT NULL,
        START_TIME BIGINT(13) NOT NULL,
        END_TIME BIGINT(13) NULL,
        CALENDAR_NAME VARCHAR(200) NULL,
        MISFIRE_INSTR SMALLINT(2) NULL,
        JOB_DATA BLOB NULL,
        PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
        FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
            REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)
    );
    
    CREATE TABLE QRTZ_SIMPLE_TRIGGERS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        TRIGGER_NAME VARCHAR(200) NOT NULL,
        TRIGGER_GROUP VARCHAR(200) NOT NULL,
        REPEAT_COUNT BIGINT(7) NOT NULL,
        REPEAT_INTERVAL BIGINT(12) NOT NULL,
        TIMES_TRIGGERED BIGINT(10) NOT NULL,
        PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
        FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
            REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    );
    
    CREATE TABLE QRTZ_CRON_TRIGGERS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        TRIGGER_NAME VARCHAR(200) NOT NULL,
        TRIGGER_GROUP VARCHAR(200) NOT NULL,
        CRON_EXPRESSION VARCHAR(200) NOT NULL,
        TIME_ZONE_ID VARCHAR(80),
        PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
        FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
            REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    );
    
    CREATE TABLE QRTZ_SIMPROP_TRIGGERS
      (          
        SCHED_NAME VARCHAR(120) NOT NULL,
        TRIGGER_NAME VARCHAR(200) NOT NULL,
        TRIGGER_GROUP VARCHAR(200) NOT NULL,
        STR_PROP_1 VARCHAR(512) NULL,
        STR_PROP_2 VARCHAR(512) NULL,
        STR_PROP_3 VARCHAR(512) NULL,
        INT_PROP_1 INT NULL,
        INT_PROP_2 INT NULL,
        LONG_PROP_1 BIGINT NULL,
        LONG_PROP_2 BIGINT NULL,
        DEC_PROP_1 NUMERIC(13,4) NULL,
        DEC_PROP_2 NUMERIC(13,4) NULL,
        BOOL_PROP_1 VARCHAR(1) NULL,
        BOOL_PROP_2 VARCHAR(1) NULL,
        PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
        FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) 
        REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    );
    
    CREATE TABLE QRTZ_BLOB_TRIGGERS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        TRIGGER_NAME VARCHAR(200) NOT NULL,
        TRIGGER_GROUP VARCHAR(200) NOT NULL,
        BLOB_DATA BLOB NULL,
        PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
        FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
            REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    );
    
    CREATE TABLE QRTZ_CALENDARS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        CALENDAR_NAME  VARCHAR(200) NOT NULL,
        CALENDAR BLOB NOT NULL,
        PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)
    );
    
    CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        TRIGGER_GROUP  VARCHAR(200) NOT NULL, 
        PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)
    );
    
    CREATE TABLE QRTZ_FIRED_TRIGGERS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        ENTRY_ID VARCHAR(95) NOT NULL,
        TRIGGER_NAME VARCHAR(200) NOT NULL,
        TRIGGER_GROUP VARCHAR(200) NOT NULL,
        INSTANCE_NAME VARCHAR(200) NOT NULL,
        FIRED_TIME BIGINT(13) NOT NULL,
        SCHED_TIME BIGINT(13) NOT NULL,
        PRIORITY INTEGER NOT NULL,
        STATE VARCHAR(16) NOT NULL,
        JOB_NAME VARCHAR(200) NULL,
        JOB_GROUP VARCHAR(200) NULL,
        IS_NONCONCURRENT VARCHAR(1) NULL,
        REQUESTS_RECOVERY VARCHAR(1) NULL,
        PRIMARY KEY (SCHED_NAME,ENTRY_ID)
    );
    
    CREATE TABLE QRTZ_SCHEDULER_STATE
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        INSTANCE_NAME VARCHAR(200) NOT NULL,
        LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
        CHECKIN_INTERVAL BIGINT(13) NOT NULL,
        PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)
    );
    
    CREATE TABLE QRTZ_LOCKS
      (
        SCHED_NAME VARCHAR(120) NOT NULL,
        LOCK_NAME  VARCHAR(40) NOT NULL, 
        PRIMARY KEY (SCHED_NAME,LOCK_NAME)
    );
    

     quartz.properties文件:

    org.quartz.scheduler.instanceName = MyScheduler
    org.quartz.threadPool.threadCount = 3
    org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
    org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    org.quartz.jobStore.tablePrefix = QRTZ_
    org.quartz.jobStore.dataSource = myDS
    
    org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
    org.quartz.dataSource.myDS.URL = jdbc:mysql://10.7.5.2:3306/matrix?useUnicode=true
    org.quartz.dataSource.myDS.user = grampus
    org.quartz.dataSource.myDS.password = 123456
    org.quartz.dataSource.myDS.maxConnections = 5
    

    Job每次都是newInstance的实例,怎么传值给它?

    每一个JobDetail都会有一个JobDataMap。JobDataMap本质就是一个Map的扩展类,只是提供了一些更便捷的方法。可以使用JobDataMap为Job传值。

    package com.mryx.matrix.codeanalyzer.core.service.impl;
    
    import com.mryx.common.utils.StringUtils;
    import com.mryx.matrix.codeanalyzer.core.service.JobManagerService;
    import com.mryx.matrix.codeanalyzer.core.service.P3cCodeScanJobService;
    import com.mryx.matrix.codeanalyzer.core.service.ProjectCodeScanTaskService;
    import com.mryx.matrix.codeanalyzer.core.service.ProjectPmdScanTaskService;
    import com.mryx.matrix.codeanalyzer.domain.CodeScanJob;
    import com.mryx.matrix.codeanalyzer.domain.CodeScanResult;
    import org.quartz.CronScheduleBuilder;
    import org.quartz.CronTrigger;
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.JobKey;
    import org.quartz.Scheduler;
    import org.quartz.SchedulerFactory;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.TriggerKey;
    import org.quartz.impl.StdSchedulerFactory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    
    @Service("jobManagerService")
    public class JobManagerServiceImpl implements JobManagerService {
        private static Logger logger = LoggerFactory.getLogger(JobManagerServiceImpl.class);
        private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    
        @Override
        public boolean addJob(Class jobClass, String remote, CodeScanJob codeScanJob, String jobId, ProjectCodeScanTaskService projectCodeScanTaskService) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                String jobName = codeScanJob.getAppCode()+size;
                String jobGroupName = codeScanJob.getCodeBranch();
                String triggerName = codeScanJob.getAppCode()+size;
                String triggerGroupName = codeScanJob.getCodeBranch();
                ++size;
                if (StringUtils.isEmpty(jobName) || StringUtils.isEmpty(jobGroupName) || StringUtils.isEmpty(triggerName) || StringUtils.isEmpty(triggerGroupName)) {
                    logger.error("任务名、任务组名、触发器名、触发器组名不能为空");
                    return false;
                } else {
                    // 任务名,任务组,任务执行类
                    JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
    
                    // 触发器
                    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                    // 触发器名,触发器组
                    triggerBuilder.withIdentity(triggerName, triggerGroupName);
                    triggerBuilder.startNow();
                    // 触发器时间设定
                    triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule("0 10 18 * * ?"));
                    logger.info("定时任务触发时间是{}", codeScanJob.getTimeTrigger());
                    // 创建Trigger对象
                    CronTrigger trigger = (CronTrigger) triggerBuilder.build();
    
                    jobDetail.getJobDataMap().put("remote", remote);
                    jobDetail.getJobDataMap().put("codeScanJob", codeScanJob);
                    jobDetail.getJobDataMap().put("jobId", jobId);
                    jobDetail.getJobDataMap().put("projectCodeScanTaskService", projectCodeScanTaskService);
                    // 调度容器设置JobDetail和Trigger
                    sched.scheduleJob(jobDetail, trigger);
    
                    // 启动
                    if (!sched.isShutdown()) {
                        sched.start();
                        logger.info("添加定时任务成功");
                        return true;
                    }
                }
            } catch (Exception e) {
                logger.error("添加定时任务失败 {}",e);
                return false;
            }
            return false;
        }
    
        /**
         * @param jobName
         * @param jobGroupName
         * @param triggerName      触发器名
         * @param triggerGroupName 触发器组名
         * @param cron             时间设置,参考quartz说明文档
         * @Description: 修改一个任务的触发时间
         */
        @Override
        public boolean modifyJobTime(String jobName,
                                     String jobGroupName, String triggerName, String triggerGroupName, String cron) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
                CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
                if (trigger == null) {
                    return false;
                }
    
                String oldTime = trigger.getCronExpression();
                if (!oldTime.equalsIgnoreCase(cron)) {
                    /** 方式一 :调用 rescheduleJob 开始 */
                    // 触发器
                    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                    // 触发器名,触发器组
                    triggerBuilder.withIdentity(triggerName, triggerGroupName);
                    triggerBuilder.startNow();
                    // 触发器时间设定
                    triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                    // 创建Trigger对象
                    trigger = (CronTrigger) triggerBuilder.build();
                    // 方式一 :修改一个任务的触发时间
                    sched.rescheduleJob(triggerKey, trigger);
                    /** 方式一 :调用 rescheduleJob 结束 */
    
                    /** 方式二:先删除,然后在创建一个新的Job  */
                    //JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                    //Class<? extends Job> jobClass = jobDetail.getJobClass();
                    //removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                    //addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);
                    /** 方式二 :先删除,然后在创建一个新的Job */
                    logger.info("修改任务触发时间成功");
                    return true;
                }
            } catch (Exception e) {
                logger.error("修改任务触发时间失败");
                return false;
            }
            return false;
        }
    
        /**
         * @param jobName
         * @param jobGroupName
         * @param triggerName
         * @param triggerGroupName
         * @Description: 移除一个任务
         */
        @Override
        public boolean removeJob(String jobName, String jobGroupName,
                                 String triggerName, String triggerGroupName) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
    
                TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
    
                sched.pauseTrigger(triggerKey);// 停止触发器
                sched.unscheduleJob(triggerKey);// 移除触发器
                sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
                logger.info("移除任务成功");
                return true;
            } catch (Exception e) {
                logger.error("移除任务失败");
            }
            return false;
        }
    
        @Override
        public boolean removeJob(CodeScanJob codeScanJob) {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                String triggerName = codeScanJob.getAppCode();
                String triggerGroupName = codeScanJob.getAppCode();
                String jobName = codeScanJob.getAppCode();
                String jobGroupName = codeScanJob.getAppCode();
                if (StringUtils.isEmpty(jobName) || StringUtils.isEmpty(jobGroupName) || StringUtils.isEmpty(triggerName) || StringUtils.isEmpty(triggerGroupName)) {
                    logger.info("无法移除任务");
                    return false;
                } else {
                    TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
    
                    sched.pauseTrigger(triggerKey);// 停止触发器
                    sched.unscheduleJob(triggerKey);// 移除触发器
                    sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
                    logger.info("移除任务成功");
                    return true;
                }
            } catch (Exception e) {
                logger.error("移除任务失败");
            }
            return false;
        }
    
        /**
         * @Description:启动所有定时任务
         */
        @Override
        public boolean startJobs() {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                sched.start();
                logger.info("启动所有定时任务成功");
                return true;
            } catch (Exception e) {
                logger.error("启动所有定时任务失败");
            }
            return false;
        }
    
        /**
         * @Description:关闭所有定时任务
         */
        @Override
        public boolean shutdownJobs() {
            try {
                Scheduler sched = schedulerFactory.getScheduler();
                if (!sched.isShutdown()) {
                    sched.shutdown();
                    logger.info("关闭所有定时任务成功");
                    return true;
                }
            } catch (Exception e) {
                logger.error("关闭所有定时任务失败");
            }
            return false;
        }
    }
    
    package com.mryx.matrix.codeanalyzer.core.task;
    
    import com.alibaba.fastjson.JSONObject;
    import com.google.common.collect.Maps;
    import com.mryx.common.utils.HttpClientUtil;
    import com.mryx.common.utils.HttpPoolClient;
    import com.mryx.matrix.codeanalyzer.core.service.ProjectCodeScanTaskService;
    import com.mryx.matrix.codeanalyzer.domain.CodeScanJob;
    import com.mryx.matrix.codeanalyzer.domain.CodeScanJobRecord;
    import org.quartz.Job;
    import org.quartz.JobDataMap;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;
    import java.util.Optional;
    
    public class P3cScanJob implements Job {
        private static Logger logger = LoggerFactory.getLogger(P3cScanJob.class);
        private static final HttpPoolClient HTTP_POOL_CLIENT = HttpClientUtil.create(150000, 150000, 5, 5, 0, 150000);
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            try {
                JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
    
                String remote = dataMap.getString("remote");
                String jobId = dataMap.getString("jobId");
                ProjectCodeScanTaskService projectCodeScanTaskService = (ProjectCodeScanTaskService) dataMap.get("projectCodeScanTaskService");
                CodeScanJob codeScanJob = (CodeScanJob) dataMap.get("codeScanJob");
                String gitAddress = codeScanJob.getGitAddress();
                String codeBranch = codeScanJob.getCodeBranch();
                String runUserName = codeScanJob.getRunUserName();
                CodeScanJobRecord codeScanJobRecord = new CodeScanJobRecord();
                codeScanJobRecord.setJobId(Integer.valueOf(jobId));
                codeScanJobRecord.setRunUserName(runUserName);
                codeScanJobRecord.setManualOrAutomatic(1);
                codeScanJobRecord.setCodeScanTime(new Date());
                codeScanJobRecord.setTypeOfScan(2);
                codeScanJobRecord.setJobStatus(5);
                synchronized (P3cScanJob.class) {
                    Integer insertRecord = projectCodeScanTaskService.insertP3cRecord(codeScanJobRecord);
                    if (insertRecord > 0) {
                        logger.info("jobID is {}", jobId);
                        Integer recordId = projectCodeScanTaskService.getRecordIdByJobId(codeScanJobRecord);
                        if (recordId > 0) {
                            logger.info("recordId is {}", recordId);
                            codeScanJob.setId(Integer.valueOf(jobId));
                            String sendId = jobId + "a" + recordId;
                            Map<String, Object> parameters = getParameters(gitAddress, codeBranch, sendId);
                            logger.info("本次p3c扫描请求参数是{},{}", remote, parameters);
                            Optional<String> scanResult = HTTP_POOL_CLIENT.postJson(remote, JSONObject.toJSONString(parameters));
                            if (scanResult.isPresent()) {
                                logger.info("p3c扫描任务创建成功,已经成功调用对方接口,{} ", scanResult);
                            } else {
                                logger.error("p3c扫描任务创建请求失败");
                            }
                        } else {
                            logger.error("获取任务记录ID失败");
                        }
                    } else {
                        logger.error("任务记录入库失败");
                    }
                }
            } catch (Exception e) {
                logger.error("p3c扫描任务创建请求失败{}", e);
            }
        }
    
        private Map<String, Object> getParameters(String gitAddress, String codeBranch, String jobId) {
            Map<String, Object> parameters = Maps.newHashMap();
            parameters.put("git", gitAddress);
            parameters.put("branch", codeBranch);
            parameters.put("id", jobId);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
            String date = df.format(new Date());
            parameters.put("time", date);
            return parameters;
        }
    }
    

    参考:

    https://blog.csdn.net/xlxxcc/article/details/52115995

    https://yq.aliyun.com/articles/29122

    https://blog.csdn.net/stormdony/article/details/80218223

    https://blog.csdn.net/stormdony/article/details/79779972

  • 相关阅读:
    C语言学习之指针
    IT人和普洱茶
    茶如人生 你是什么茶?
    普洱茶的冲泡技巧
    普洱茶保健功效
    廖雪峰Python总结3
    廖雪峰Python总结2
    Linux之软件包安装管理
    Linux常用命令6 关机重启命令
    Linux之Vim编辑器
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10134170.html
Copyright © 2020-2023  润新知