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