登录
首页 >  数据库 >  MySQL

Quartz-任务进度管理器

来源:SegmentFault

时间:2023-02-24 13:03:29 125浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是数据库学习者,那么本文《Quartz-任务进度管理器》就很适合你!本篇内容主要包括Quartz-任务进度管理器,希望对大家的知识积累有所帮助,助力实战开发!

Quartz简介-参考链接

Quartz是完全由

//调度标识名 集群中每一个实例都必须使用相同的名称 (区分特定的调度器实例)
org.quartz.scheduler.instanceName:DefaultQuartzScheduler
//ID设置为自动获取 每一个必须不同 (所有调度器实例中是唯一的)
org.quartz.scheduler.instanceId :AUTO
//数据保存方式为持久化 
org.quartz.jobStore.class :org.quartz.impl.jdbcjobstore.JobStoreTX
//表的前缀 
org.quartz.jobStore.tablePrefix : QRTZ_
//设置为TRUE不会出现序列化非字符串类到 BLOB 时产生的类版本问题
//org.quartz.jobStore.useProperties : true
//加入集群 true 为集群 false不是集群
org.quartz.jobStore.isClustered : false
//调度实例失效的检查时间间隔 
org.quartz.jobStore.clusterCheckinInterval:20000 
//容许的最大作业延长时间 
org.quartz.jobStore.misfireThreshold :60000
//ThreadPool 实现的类名 
org.quartz.threadPool.class:org.quartz.simpl.SimpleThreadPool
//线程数量 
org.quartz.threadPool.threadCount : 10
//线程优先级 
org.quartz.threadPool.threadPriority : 5(threadPriority 属性的最大值是常量 java.lang.Thread.MAX_PRIORITY,等于10。最小值为常量 java.lang.Thread.MIN_PRIORITY,为1)
//自创建父线程
//org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true 
//数据库别名
org.quartz.jobStore.dataSource : qzDS
//设置数据源
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/quartz
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:123456
org.quartz.dataSource.qzDS.maxConnection:10
demo实例

RAM方式

引入依赖

 
        org.quartz-schedulerquartz2.2.1org.quartz-schedulerquartz-jobs2.2.1ch.qos.logbacklogback-classic1.0.11

Job类

package com.zyc;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RAMJob implements Job{

    private static Logger logger = LoggerFactory.getLogger(RAMJob.class);


    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        logger.info("Say hello to Quartz" + new Date());
    }

}

测试类 CronScheduleBuilder

import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RAMQuartzTest {

    private static Logger _log = LoggerFactory.getLogger(RAMQuartzTest.class);

    public static void main(String[] args) throws SchedulerException {
        //1.创建Scheduler的工厂
        SchedulerFactory sf = new StdSchedulerFactory();
        //2.从工厂中获取调度器实例
        Scheduler scheduler = sf.getScheduler();


        //3.创建JobDetail
        JobDetail jb = JobBuilder.newJob(RAMJob.class)
                .withDescription("this is a ram job") //job的描述
                .withIdentity("ramJob", "ramGroup") //job 的name和group
                .build();

        //任务运行的时间,SimpleSchedle类型触发器有效
        long time=  System.currentTimeMillis() + 13*1000L; //13秒后启动任务
        Date statTime = new Date(time);

        //4.创建Trigger
        //使用SimpleScheduleBuilder或者CronScheduleBuilder
        Trigger t = TriggerBuilder.newTrigger()
                .withDescription("")
                .withIdentity("ramTrigger", "ramTriggerGroup")
                //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
                .startAt(statTime)  //默认当前时间启动
                .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
                .build();

        //5.注册任务和定时器
        scheduler.scheduleJob(jb, t);

        //6.启动 调度器
        scheduler.start();
        _log.info("启动时间 : " + new Date());
        //scheduler.shutdown();

    }
}

SimpleScheduleBuilder

       //4.创建Trigger
       //使用SimpleScheduleBuilder或者CronScheduleBuilder
       Trigger t = TriggerBuilder.newTrigger()
               .withDescription("")
               .withIdentity("ramTrigger", "ramTriggerGroup")
               .withSchedule(SimpleScheduleBuilder.simpleSchedule())
               .startAt(statTime)  //默认当前时间启动
//                .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
               .build();
SpringBoot集成Quartz实例

引入pom依赖

       org.springframework.bootspring-boot-starter-quartz

配置Quartz的配置

.properties

###################### quartz begin ##############################
spring.quartz.job-store-type=jdbc
spring.quartz.properties.org.quartz.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.quartz.properties.org.quartz.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.quartz.properties.org.quartz.datasource.username=root
spring.quartz.properties.org.quartz.datasource.password=123456
spring.quartz.properties.org.quartz.scheduler.instancName=clusteredScheduler
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
spring.quartz.properties.org.quartz.jobStore.tablePrefix=qrtz_
spring.quartz.properties.org.quartz.jobStore.isClustered=true
spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=1000
spring.quartz.properties.org.quartz.jobStore.useProperties=false
spring.quartz.properties.org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
spring.quartz.properties.org.quartz.threadPool.threadCount=20
spring.quartz.properties.org.quartz.threadPool.threadPriority=5
###################### quartz begin ##############################

.yml

spring:
  quartz:
    job-store-type: jdbc
    properties:
      org:
        quartz:
          datasource:
            driver-class-name: com.mysql.cj.jdbc.Driver
            url: jdbc:mysql://localhost:3306/data?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true
            username: root
            password: root
          scheduler:
            instancName: clusteredScheduler
            instanceId: AUTO
          jobStore:
            class: org.quartz.impl.jdbcjobstore.JobStoreTX
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            tablePrefix: qrtz_
            isClustered: true
            clusterCheckinInterval: 1000
            useProperties: false
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool
            threadCount: 20
            threadPriority: 5

实现Job接口,实现业务调度

@Slf4j
public class TaskExecuteJob implements Job {
    
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
      //执行业务调度
        String taskId = context.getJobDetail().getKey().toString();
        String[] s = taskId.split("_");
        if (s.length > 1) {
            taskId = s[1].replace(".J", "");
            log.info("调度任务 --> taskId: " + taskId);
        }
    }

}

Quartz调度器

@Component
@Slf4j
public class QuartzManager {

    @Resource
    SchedulerFactoryBean schedulerFactory;

    @Resource
    private Scheduler scheduler;

    /**
     * @param id
     * @param date
     * @param type
     * @return
     */
    public Map addTaskJob(String id, Date date, String type) {
        String cron = getCron(date);

        log.info("cron事件表达式 --> " + cron);

        Map map = setData(id);

        if (Constant.TASK.equals(type)) {
            addJob(map.get("jobName"), map.get("jobGroupName"), map.get("triggerName"), map.get("triggerGroupName"), TaskExecuteJob.class, cron);
        }
        return map;
    }

    public Map deleteTaskJob(String id) {
        Map map = setData(id);
        removeJob(map.get("jobName"), map.get("jobGroupName"), map.get("triggerName"), map.get("triggerGroupName"));
        log.info("删除定时任务 --> " + map.get("jobName"));
        return map;
    }

    public Map setData(String id) {
        Map map = new HashMap(16);
        map.put("jobName", "J_" + id);
        map.put("jobGroupName", "G_" + id);
        map.put("triggerName", "T_" + id);
        map.put("triggerGroupName", "TG_" + id);
        return map;
    }

    /**
     * Date格式转成cron格式
     *
     * @param date Date事件
     * @return cron格式
     */
    private String getCron(Date date) {
        StringBuilder sb = new StringBuilder();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        sb.append(calendar.get(Calendar.SECOND));
        sb.append(" ");
        sb.append(calendar.get(Calendar.MINUTE));
        sb.append(" ");
        sb.append(calendar.get(Calendar.HOUR_OF_DAY));
        sb.append(" ");
        sb.append(calendar.get(Calendar.DATE));
        sb.append(" ");
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append(" ?");

        return sb.toString();
    }

    /**
     * 添加一个定时任务
     *
     * @param jobName          任务名
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass         任务
     * @param cron             时间设置,参考quartz说明文档
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String cron) {
        try {
            scheduler = schedulerFactory.getScheduler();
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            log.info("添加任务出现异常!,{}", e.getMessage());
        }
    }

    /**
     * 修改一个任务的触发时间
     *
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param cron             时间设置,参考quartz说明文档
     */
    public void modifyJobTime(String triggerName, String triggerGroupName, String cron) {
        try {
            scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                trigger = (CronTrigger) triggerBuilder.build();
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            log.info("修改任务出现异常!,{}", e.getMessage());
        }
    }

    /**
     * 移除一个任务
     *
     * @param jobName          任务名
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     */
    public void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {
            scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
        } catch (Exception e) {
            log.info("移除任务出现异常!,{}", e.getMessage());
        }
    }
}

今天关于《Quartz-任务进度管理器》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表