首页 > 其他分享 >Quartz组件的搭建及实现任务调度demo

Quartz组件的搭建及实现任务调度demo

时间:2023-03-15 13:11:57浏览次数:38  
标签:Quartz demo private ResultModel 任务 taskJob put new 任务调度

1.基本环境配置

<dependency>
​    <groupId>org.slf4j</groupId>
​    <artifactId>slf4j-log4j12</artifactId>
​    <version>1.7.25</version>
​</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.3</version>
</dependency>

2.demo的封装及使用

2.1 TaskJob实体类

@Data
@ApiModel(value = "调度任务表")
public class TaskJob  extends BaseEntity {
    @ApiModelProperty(value="定时任务ID")
    private Long jobId;
    @ApiModelProperty(value="定时任务组")
    private String jobGroup;
    @ApiModelProperty(value="定时任务名称")
    private String jobName;
    @ApiModelProperty(value="任务开始时间")
    private Date startTime;
    @ApiModelProperty(value="任务结束时间")
    private Date endTime;
    @ApiModelProperty(value="cron表达式")
    private String cronExpression;
    @ApiModelProperty(value="任务执行时调用哪个类的方法 包名+类名 例如 com.nbs.RunJob")
    private String jobClassName;
    @ApiModelProperty(value="参数")
    private String jsonParam;
    @ApiModelProperty(value="任务状态 0.正运行 1.已停止")
    private Integer jobStatus;

    @Override
    public HashMap<String, String> getColumnMap(){return columnMap;}
    @Override
    public HashMap<String, String> getTableMap(){return tableMap;}
    @Override
    public HashMap<String, String> getSqlMap(){return sqlMap;}
    private static final HashMap<String, String> columnMap = new HashMap(){{
        put("任务ID", "t.jobId");
        put("任务组", "t.jobGroup");
        put("任务名称", "t.jobName");
        put("任务开始时间", "t.startTime");
        put("任务结束时间", "t.endTime");
        put("cron表达式", "t.cronExpression");
        put("调用类", "t.jobClassName");
        put("任务状态", "t.jobStatus");
        put("备注", "t.remark");
        put("创建时间", "t.createTime");
        put("创建人", "t.createUserName");
        put("编辑时间", "t.updateTime");
        put("编辑人", "t.updateUserName");
        put("是否删除","t.delFlag");
    }};
    private final static HashMap<String, String> tableMap = new HashMap(){{
        put("list","TaskJob  as t");
        put("dropList","TaskJob as t");
    }};
    private final static HashMap<String, String> sqlMap = new HashMap(){{
        put("任务状态","case when t.jobStatus=0 then '正运行' else '启用' 已停止");
    }};
}

2.2 QuartzUtil工具类

public class QuartzUtil {
    /**
     * 创建任务
     *
     * @param taskJob
     * @throws SchedulerException
     * @throws ClassNotFoundException
     */
    public ResultModel createTaskJob(Scheduler scheduler,TaskJob taskJob) throws SchedulerException, ClassNotFoundException {
        //任务执行类
        Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(taskJob.getJobClassName());
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(taskJob.getJobName(), taskJob.getJobGroup()).build();
        if (StringUtil.isNotEmpty(taskJob.getJsonParam())) {
            JSONObject jsonObject = JSON.parseObject(taskJob.getJsonParam());
            for (String key : jsonObject.keySet()) {
                jobDetail.getJobDataMap().put(key, jsonObject.get(key));
            }
        }
        TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger().withIdentity(taskJob.getJobName(), taskJob.getJobGroup());
        triggerBuilder.usingJobData(jobDetail.getJobDataMap());
        if (StringUtil.isNotEmpty(taskJob.getCronExpression())) {
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(taskJob.getCronExpression());
            // 按新的cronExpression表达式构建一个新的trigger
            triggerBuilder.withSchedule(scheduleBuilder);
        } else {
            throw new ConcurrentException(new ResultModel(false, ResultModel.DATA_ERROR, "定时器启动失败,未设置时间表达式且未设置间隔时间"));
        }


        if (taskJob.getStartTime() != null && taskJob.getStartTime().getTime() > new Date().getTime()) {
            triggerBuilder.startAt(taskJob.getStartTime());
        }
        if (taskJob.getEndTime() != null) {
            if (taskJob.getEndTime().getTime() <= new Date().getTime()) {
                //结束时间早于现在,直接不用执行了
                return new ResultModel(false, ResultModel.DATA_ERROR, "定时器启动失败,结束时间早于开始时间!");
            }
            triggerBuilder.endAt(taskJob.getEndTime());
        }
        scheduler.scheduleJob(jobDetail, triggerBuilder.build());
        return new ResultModel(true, ResultModel.SUCCESS, "启动成功!");
    }



    /**
     * 获取任务状态
     *
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
    public JobInfo getJobInfo(Scheduler scheduler,String jobName, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        JobInfo info = new JobInfo();
        info.setJobName(jobName);
        info.setJobGroup(jobGroup);
        info.setCronExpression(cronTrigger.getCronExpression());
        info.setJobStatus(scheduler.getTriggerState(triggerKey).name());
        return info;
    }


    /**
     * 删除任务
     *
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    public ResultModel deleteJob(Scheduler scheduler,String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail != null) {
            scheduler.deleteJob(jobKey);
        }
        return new ResultModel(true, ResultModel.SUCCESS, "启动成功!");
    }


    public static TriggerKey getTriggerKey(String jobName, String jobGroup) {
        return TriggerKey.triggerKey(jobName, jobGroup);
    }

    public ResultModel  saveTaskJob(Scheduler scheduler,TaskJob taskJob) {
        TriggerKey triggerKey=TriggerKey.triggerKey(taskJob.getJobName(),taskJob.getJobGroup());
        if (triggerKey==null){
            try {
                return createTaskJob(scheduler, taskJob);
            }catch (Exception ex){
                return new ResultModel(false,ResultModel.CHECK_ERROR,ex.getMessage());
            }
        } else {
            try {
                return updateTaskJob(scheduler,taskJob);
            }catch (Exception ex){
                return new ResultModel(false,ResultModel.CHECK_ERROR,ex.getMessage());
            }
        }
    }


    /**
     * 更新任务
     * @throws SchedulerException
     */
    public ResultModel  updateTaskJob(Scheduler scheduler,TaskJob taskJob) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(taskJob.getJobName(),taskJob.getJobGroup());
        //表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(taskJob.getCronExpression());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

        if (StringUtil.isNotEmpty(taskJob.getJsonParam())) {
            JSONObject jsonObject = JSON.parseObject(taskJob.getJsonParam());
            for (String key : jsonObject.keySet()) {
                trigger.getJobDataMap().put(key, jsonObject.get(key));
            }
        }

        if ((taskJob.getStartTime()!=null) && (taskJob.getEndTime()!=null)){
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).startAt(taskJob.getStartTime()).endAt(taskJob.getEndTime()).withSchedule(scheduleBuilder).build();
        } else {
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        }

        //按新的trigger重新设置job执行
        scheduler.rescheduleJob(triggerKey, trigger);
        return new ResultModel(true, ResultModel.SUCCESS, "启动成功!");
    }
}

2.3 TaskJobServiceImpl实现类调用QuartzUtil方法

(1)、新增调度任务调用创建调度方法

try{
    return quartzUtil.createTaskJob(scheduler, entity);
}catch (Exception ex){
    throw new ConcurrentException(new ResultModel(false, ResultModel.BUSINESS_ERROR, "添加调度任务失败,原因:"+ex.getMessage() ));
}

(2)、修改调度任务调用saveTaskJob调度方法

try{
    if (entity.getJobStatus()==0) { //判断正在启用的调度任务方法
        return quartzUtil.saveTaskJob(scheduler, entity);
    } else {
        return new ResultModel(true, ResultModel.SUCCESS, "成功!");
    }

}catch (Exception ex){
    throw new ConcurrentException(new ResultModel(false, ResultModel.BUSINESS_ERROR, "添加调度任务失败,原因:"+ex.getMessage() ));
}

(3)、删除调度任务调用deleteJob调度方法

try{
    return quartzUtil.deleteJob(scheduler, job.getJobName(),job.getJobGroup());
}catch (Exception ex){
    throw new ConcurrentException(new ResultModel(false, ResultModel.BUSINESS_ERROR, "添加调度任务失败,原因:"+ex.getMessage() ));
}

(4)、启用所有调度任务

List<TaskJob> jobs=taskJobDAO.selectByParams(null);

for (TaskJob job:jobs){
    try {
       ResultModel rm= quartzUtil.createTaskJob(scheduler, job);
       if (rm.isSuccess()){
           taskJobDAO.updateJobStatus(job.getJobId(),0);
       } else {
           taskJobDAO.updateJobStatus(job.getJobId(),1);
       }
    }catch (Exception ex)
    {
        System.out.println("启动所有任务,失败原因:"+ex.getMessage());
    }
}

5)、启停调度任务

if  (jobStatus==0){
    quartzUtil.createTaskJob(scheduler, job);
} else {
    quartzUtil.deleteJob(scheduler, job.getJobName(),job.getJobGroup());
}

3.调度任务web页面创建

4.OrderPrintTestJob业务类

@Slf4j
//保持单例不并发(集群会出现重复执行任务问题)
@DisallowConcurrentExecution
public class OrderPrintTestJob implements Job, Serializable {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        JobDataMap dataMap = jobExecutionContext.getTrigger().getJobDataMap();
        String  myName = dataMap.get("myName").toString();
        System.out.println("*******************这是我要打印的内容[OrderPrintTestJob],参数:"+myName+",时间:"+DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss")  +"*******************");
    }
}

5.配置类开启计划任务的支持

@EnableScheduling
public class NbsBusinessCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(NbsBusinessCenterApplication.class, args);
    }
}

 

 

标签:Quartz,demo,private,ResultModel,任务,taskJob,put,new,任务调度
From: https://www.cnblogs.com/z7298128/p/17218115.html

相关文章

  • FreeRTOS 任务调度
    【FreeRTOS】05任务的调度:抢占式、协作式、时间片轮转_freertos抢占式_xiaobaibai_2021的博客-CSDN博客1、FreeRTOS的任务调度方法有抢占式、时间片轮转、协作式。2、抢......
  • 一个demo学会java
    全栈工程师开发手册(作者:栾鹏)快捷链接:​java开发大全这篇demo较长,包含了java基本的内容,若不是出于校验自己java基础能力的朋友,建议按照上面的链接分章节学习。本demo包含了j......
  • Java 建造者模式/链式调用 简单Demo
    最近,公司同事要求我给他们讲一下RxJava,为了更清晰的说明其架构,.简单写了一个链式调用的小Demo,分享给大家/**作者:赵星海(CSDN-深海呐)*时间:2019年3月19日16:56:32*......
  • 修改node项目自动重启 | nodemon工具包
    1、为什么使用nodemon(1)在编写调试Node.js项目的时候,如果修改了项目的代码,则需要频繁的手动close掉,然后再重新启动,非常繁琐。现在,我们可以使用nodemon工具包这个工......
  • Java实现一个轻量的DAG任务调度demo
    DAG(DirectedAcyclicGraph,有向无环图)是指一个有向图,其中不包含任何环。在任务调度中,DAG被用来表示任务之间的依赖关系。一个任务的执行必须等待其依赖的任务完成之后才能......
  • Java实现一个轻量的跳表demo
    importjava.util.Random;publicclassSkipList{privatefinalstaticintMAX_LEVEL=16;privateNodehead=newNode(MAX_LEVEL,0);privateRa......
  • Spel表达demo
    packagecom.example.demo;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.context.......
  • laravel之任务调度(定时任务)
      常用命令:#开启任务调度(一般在服务器添加定时任务每分钟执行一次)phpartisanschedule:run  总结:1.runInBackground在不使用runInBackground的方......
  • typescript 接口demo
    https://www.runoob.com/typescript/ts-interface.html......
  • mybatis-plus(mp)常用概念以及demo实操
    概念:作为国内流行的持久层框架,mp是mybatis的拓展,并不改变mybaits的底层,因此使用mybatis的项目可以无缝使用mp进行迭代本博客旨在温习mp常用的使用场景、使用方式(一)demo框......