1. 程式人生 > 其它 >spring-boot整合Quartz-job儲存方式二RAM

spring-boot整合Quartz-job儲存方式二RAM

1、jar包依賴引入

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

2、yml配置檔案

  quartz:
    properties:
      org:
        quartz:
          scheduler:
            instanceName: quartzScheduler
            instanceId: AUTO
          threadPool:
            
class: org.quartz.simpl.SimpleThreadPool threadCount: 10 threadPriority: 5 threadsInheritContextClassLoaderOfInitializingThread: true

3、實體類SysQuartzramJob

package org.jeecg.modules.quartz.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.jeecgframework.poi.excel.annotation.Excel; /** * @Description: 定時任務RAM, *
@author: dengjie * @Date: 2022-02-16 * @Version: V1.0 */ @Data @TableName("sys_quartz_job_ram") @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="sys_quartz_job_ram物件", description="定時任務RAM") public class SysQuartzramJob { //名字和分組,定好了就不能改,切記。定時器內部核心邏輯是根據名字和分組去標識一個定時任務的 /**id*/ @TableId(type = IdType.ID_WORKER_STR) @ApiModelProperty(value = "id") private String id; /**任務名稱*/ @Excel(name = "任務名稱", width = 15) @ApiModelProperty(value = "任務名稱") private String jobName; /**任務分組*/ @Excel(name = "任務分組", width = 15) @ApiModelProperty(value = "任務分組") private String jobGroup; /**執行類*/ @Excel(name = "執行類", width = 15) @ApiModelProperty(value = "執行類") private String jobClassName; /**執行時間*/ @Excel(name = "執行時間", width = 15) @ApiModelProperty(value = "執行時間") private String cronExpression; /**任務狀態*/ @Excel(name = "任務狀態", width = 15) @ApiModelProperty(value = "任務狀態") private String triggerState; /**描述*/ @Excel(name = "描述", width = 15) @ApiModelProperty(value = "描述") private String description; /**下面是實體對應資料庫的表sys_quartzram_job * * CREATE TABLE "public"."sys_quartzram_job" ( * "id" varchar(50) , * "job_name" varchar(50) COLLATE "pg_catalog"."default", * "job_group" varchar(50) COLLATE "pg_catalog"."default", * "job_class_name" varchar(100) COLLATE "pg_catalog"."default", * "cron_expression" varchar(100) COLLATE "pg_catalog"."default", * "trigger_state" varchar(15) COLLATE "pg_catalog"."default", * "description" varchar(100) COLLATE "pg_catalog"."default", * CONSTRAINT "sys_quartz_job_ram_pkey" PRIMARY KEY ("id") * ) * ; * * COMMENT ON COLUMN "public"."sys_quartzram_job"."id" IS 'id'; * COMMENT ON COLUMN "public"."sys_quartzram_job"."job_name" IS '任務名稱'; * COMMENT ON COLUMN "public"."sys_quartzram_job"."job_group" IS '任務分組'; * COMMENT ON COLUMN "public"."sys_quartzram_job"."job_class_name" IS '執行類'; * COMMENT ON COLUMN "public"."sys_quartzram_job"."cron_expression" IS '執行時間'; * COMMENT ON COLUMN "public"."sys_quartzram_job"."trigger_state" IS '任務狀態'; * COMMENT ON COLUMN "public"."sys_quartzram_job"."description" IS '描述'; * */ }

4、核心controller類

package org.jeecg.modules.quartz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.quartz.entity.SysQuartzramJob;
import org.jeecg.modules.quartz.enums.JobStatus;
import org.jeecg.modules.quartz.service.ISysQuartzramJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
* @Description: 定時任務RAM
* @author: dengjie
* @Date:   2022-02-16
* @Version: V1.0
*/
@Slf4j
@Api(tags="定時任務RAM")
@RestController
@RequestMapping("/quartz/sysQuartzramJob")
public class SysQuartzramJobController extends JeecgController<SysQuartzramJob, ISysQuartzramJobService> {
    private static final String TRIGGER_IDENTITY = "trigger";
   @Autowired
   private ISysQuartzramJobService sysQuartzramJobService;
    @Autowired
    private Scheduler scheduler;
   /**
    * 分頁列表查詢
    *
    * @param sysQuartzramJob
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "定時任務RAM-分頁列表查詢")
   @ApiOperation(value="定時任務RAM-分頁列表查詢", notes="定時任務RAM-分頁列表查詢")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(SysQuartzramJob sysQuartzramJob,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<SysQuartzramJob> queryWrapper = QueryGenerator.initQueryWrapper(sysQuartzramJob, req.getParameterMap());
       Page<SysQuartzramJob> page = new Page<SysQuartzramJob>(pageNo, pageSize);
       IPage<SysQuartzramJob> pageList = sysQuartzramJobService.page(page, queryWrapper);
       return Result.ok(pageList);
   }

   /**
    * 新增
    *
    * @param sysQuartzramJob
    * @return
    */
   @AutoLog(value = "定時任務RAM-新增")
   @ApiOperation(value="定時任務RAM-新增", notes="定時任務RAM-新增")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody SysQuartzramJob sysQuartzramJob) {
       try
       {
           schedulerJob(sysQuartzramJob);
           sysQuartzramJob.setTriggerState(JobStatus.RUNNING.getStatus());
           sysQuartzramJobService.save(sysQuartzramJob);
       }
       catch (Exception e) {
            e.printStackTrace();
           return Result.error("異常:" + e.getMessage());
        }

       return Result.ok("成功!");
   }

    @AutoLog(value = "定時任務RAM-觸發")
    @ApiOperation(value="定時任務RAM-觸發", notes="定時任務RAM-觸發")
    @PostMapping(value = "/trigger")
    public Result<?> trigger(@RequestBody SysQuartzramJob sysQuartzramJob) {
        try
        {
            JobKey key = new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup());
            scheduler.triggerJob(key);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("異常:" + e.getMessage());
        }

        return Result.ok("成功!");
    }

    @AutoLog(value = "定時任務RAM-停止")
    @ApiOperation(value="定時任務RAM-停止", notes="定時任務RAM-停止")
    @PostMapping(value = "/pause")
    public Result<?> pause(@RequestBody SysQuartzramJob sysQuartzramJob) {
        try
        {
            JobKey key = new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup());
            scheduler.pauseJob(key);

            sysQuartzramJob.setTriggerState(JobStatus.PAUSED.getStatus());
            sysQuartzramJobService.updateById(sysQuartzramJob);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("異常:" + e.getMessage());
        }

        return Result.ok("成功!");
    }

    @AutoLog(value = "定時任務RAM-恢復")
    @ApiOperation(value="定時任務RAM-恢復", notes="定時任務RAM-恢復")
    @PostMapping(value = "/resume")
    public Result<?> resume(@RequestBody SysQuartzramJob sysQuartzramJob) {
        try
        {
            JobKey key = new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup());
            scheduler.resumeJob(key);

            sysQuartzramJob.setTriggerState(JobStatus.RUNNING.getStatus());
            sysQuartzramJobService.updateById(sysQuartzramJob);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("異常:" + e.getMessage());
        }

        return Result.ok("成功!");
    }

    @AutoLog(value = "定時任務RAM-刪除")
    @ApiOperation(value="定時任務RAM-刪除", notes="定時任務RAM-刪除")
    @PostMapping(value = "/delete")
    public Result<?> delete(@RequestBody SysQuartzramJob sysQuartzramJob) {
        try
        {
             String jobName=sysQuartzramJob.getJobName();
             String jobGroup=sysQuartzramJob.getJobGroup();

            TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_IDENTITY + jobName, jobGroup);
            scheduler.pauseTrigger(triggerKey);                                 // 停止觸發器
            scheduler.unscheduleJob(triggerKey);                                // 移除觸發器
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));              // 刪除任務


            sysQuartzramJobService.removeById(sysQuartzramJob.getId());
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("異常:" + e.getMessage());
        }

        return Result.ok("成功!");
    }
   /**
    * 編輯
    *
    * @param sysQuartzramJob
    * @return
    */
   @AutoLog(value = "定時任務RAM-編輯")
   @ApiOperation(value="定時任務RAM-編輯", notes="定時任務RAM-編輯")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody SysQuartzramJob sysQuartzramJob) {

       try
       {
           scheduler.deleteJob(new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup()));
           schedulerJob(sysQuartzramJob);

           sysQuartzramJobService.updateById(sysQuartzramJob);
       }
       catch (Exception e) {
           e.printStackTrace();
           return Result.error("異常:" + e.getMessage());
       }

       return Result.ok("成功!");
   }



   /**
    * 批量刪除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "定時任務RAM-批量刪除")
   @ApiOperation(value="定時任務RAM-批量刪除", notes="定時任務RAM-批量刪除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.sysQuartzramJobService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量刪除成功!");
   }

   /**
    * 通過id查詢
    *
    * @param id
    * @return
    */
   @AutoLog(value = "定時任務RAM-通過id查詢")
   @ApiOperation(value="定時任務RAM-通過id查詢", notes="定時任務RAM-通過id查詢")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       SysQuartzramJob sysQuartzramJob = sysQuartzramJobService.getById(id);
       return Result.ok(sysQuartzramJob);
   }

 /**
  * 匯出excel
  *
  * @param request
  * @param sysQuartzramJob
  */
 @RequestMapping(value = "/exportXls")
 public ModelAndView exportXls(HttpServletRequest request, SysQuartzramJob sysQuartzramJob) {
     return super.exportXls(request, sysQuartzramJob, SysQuartzramJob.class, "定時任務RAM");
 }

 /**
  * 通過excel匯入資料
  *
  * @param request
  * @param response
  * @return
  */
 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     return super.importExcel(request, response, SysQuartzramJob.class);
 }


    public void schedulerJob(SysQuartzramJob job) throws Exception {
        //構建job資訊
        Class cls = Class.forName(job.getJobClassName()) ;
        // cls.newInstance(); // 檢驗類是否存在
        JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(job.getJobName(),job.getJobGroup())
                .withDescription(job.getDescription()).build();

        // 觸發時間點
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression().trim());
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_IDENTITY + job.getJobName(), job.getJobGroup())
                .startNow().withSchedule(cronScheduleBuilder).build();
        //交由Scheduler安排觸發
        scheduler.scheduleJob(jobDetail, trigger);
    }

}

5、定時任務初始化類

程式啟動後,會自動執行ApplicationInit類,並讀取定時任務進行開始執行排程
package org.jeecg.modules.quartz.init;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.quartz.entity.SysQuartzramJob;
import org.jeecg.modules.quartz.enums.JobStatus;
import org.jeecg.modules.quartz.service.ISysQuartzramJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Component
@Slf4j
public class ApplicationInit implements CommandLineRunner {

    private static final String TRIGGER_IDENTITY = "trigger";
    @Autowired
    private ISysQuartzramJobService sysQuartzramJobService;
    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(String... args) throws Exception {

        log.info(String.format("程式啟動,定時任務開始載入,時間:" + DateUtils.getTimestamp()));

        loadJobFromDB();
    }

    //這是從資料庫表讀取定時任務的邏輯
    private void loadJobFromDB() throws Exception {
        try {

            QueryWrapper<SysQuartzramJob> queryWrapper = new QueryWrapper<SysQuartzramJob>();
            List<SysQuartzramJob> list=sysQuartzramJobService.list(queryWrapper);
            for(SysQuartzramJob job : list)
            {
                schedulerJob(job);
                if (JobStatus.PAUSED.getStatus().equals(job.getTriggerState())) {
                    scheduler.pauseJob(new JobKey(job.getJobName(), job.getJobGroup()));
                }
            }

        }
        catch (Exception e)
        {
        log.error(e.getMessage(),e);
        }
    }



    public void schedulerJob(SysQuartzramJob job) throws Exception {
        //構建job資訊
        Class cls = Class.forName(job.getJobClassName()) ;
        // cls.newInstance(); // 檢驗類是否存在
        JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(job.getJobName(),job.getJobGroup())
                .withDescription(job.getDescription()).build();

        // 觸發時間點
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression().trim());
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_IDENTITY + job.getJobName(), job.getJobGroup())
                .startNow().withSchedule(cronScheduleBuilder).build();
        //交由Scheduler安排觸發
        scheduler.scheduleJob(jobDetail, trigger);
    }
}

6、job定時任務樣例

package org.jeecg.modules.quartz.job;

import org.jeecg.common.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import lombok.extern.slf4j.Slf4j;

/**
 * 示例不帶參定時任務
 * 
 * @Author Scott
 */
@Slf4j
public class SampleJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        log.info(String.format(" Jeecg-Boot 普通定時任務 SampleJob !  時間:" + DateUtils.getTimestamp()));
    }
}

本文參考了最佳實踐博文:https://www.cnblogs.com/youzhibing/p/10208056.html