quartz使用RAMJobStore方式配置

Quartz的3个基本要素

  1. Scheduler:调度器。所有的调度都是由它控制。
  2. Trigger: 触发器。决定什么时候来执行任务。
  3. JobDetail & Job: JobDetail定义的是任务数据,而真正的执行逻辑是在Job中。使用JobDetail + Job而不是Job,这是因为任务是有可能并发执行,如果Scheduler直接使用Job,就会存在对同一个Job实例并发访问的问题。而JobDetail & Job 方式,sheduler每次执行,都会根据JobDetail创建一个新的Job实例,这样就可以规避并发访问的问题。

RAMJobStore

RAMJobStore 是使用最简单的也是最高效(依据CPU时间)的JobStore 。RAMJobStore 正如它名字描述的一样,它保存数据在RAM。

这就是为什么它是配置最简单的也是最高效的原因。缺点是你的应用结束之后所有的数据也丢失了--这意味着RAMJobStore 不具有保持job和trigger持久的能力。对于一些程序是可以接受的,甚至是期望的,但对于其他的程序可能是灾难性的。

RAMJobStore 由于job信息存储在内存中则虽然内存大小的限制,job创建的个数会受限制。

要使用RAMJobStore你只需要在你的Quartz配置文件中添上这么一段话:

org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

没有其他配置了。

当没有quartz.properties配置文件时,quartz默认使用 RAMJobStore方式

 

项目中引入相关依赖

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

我使用的項目是Springboot,因此这里我可以使用插件,如果你使用的单独的项目你可以这么配置:

    <!-- quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>${org.quartz-scheduler}</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>${org.quartz-scheduler}</version>
        </dependency>
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

job类

@Slf4j
public class RamJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("启动定时任务......");
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        log.info(jobDataMap.get("jobMessage")+":::"+jobDataMap.get("jobMessage2"));
        JobDataMap jobDataMap1 = jobExecutionContext.getTrigger().getJobDataMap();
        log.info(jobDataMap1.get("jobMessage")+":::"+jobDataMap.get("jobMessage2"));
    }
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

 创建job方法

@Slf4j
@Service
public class QuartzService {
    public static final int CRON_LIMIT = 6;

    @Autowired
    private Scheduler scheduler;

    /**
     * 创建job任务
     */
    public void createJob() throws Exception {
        createRamJob();
        createRamSecondJob();
    }

    /**
     * 创建RAMJob
     * @throws SchedulerException
     */
    public void createRamJob() throws Exception {
        String group = RamJob.class.getSimpleName();
        //获取cron表达式
        String cron = getCron("003814");
        String jobName = StringUtils.join(group, "_", "001");
        addScheduleJob(jobName,cron,group,RamJob.class);
    }

    /**
     * 创建RAMSecondJob
     * @throws SchedulerException
     */
    public void createRamSecondJob() throws Exception {
        String group = RamSecondJob.class.getSimpleName();
        //获取cron表达式
        String cron = getCron("003410");
        String jobName = StringUtils.join(group, "_", "001");
        addScheduleJob(jobName,cron,group,RamSecondJob.class);
    }

    /**
     * 根据cron组装表达式
     * @param str
     * @return
     */
    public String getCron(String str) throws Exception {
        if(str.length() != CRON_LIMIT){
            throw new Exception("cron表达式只限时分秒,字符长度需为6");
        }
        String second = str.substring(0, 2);
        String mis = str.substring(2, 4);
        String hour = str.substring(4, 6);
        String cron = second.concat(" ").concat(mis).concat(" ").concat(hour).concat(" * * ?");
        return cron;
    }

    /**
     * 添加job任务
     * @param jobName
     * @param cron
     * @param group
     * @param clazz
     */
    public void addScheduleJob(String jobName,String cron, String group, Class clazz) throws Exception {
        try {
            JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(jobName, group).build();
            jobDetail.getJobDataMap().put("jobMessage","detail信息1");
            jobDetail.getJobDataMap().put("jobMessage2","detail信息2");
            if (!CronExpression.isValidExpression(cron)) {
                //表达式格式不正确
                log.error("表达式格式不正确");
                throw new Exception("表达式格式不正确");
            }
            //调度中心不存在key时
            if(!scheduler.checkExists(jobDetail.getKey())){
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                //创建任务触发器
                Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, group).withSchedule(cronScheduleBuilder).build();
                trigger.getJobDataMap().put("jobMessage","trigger信息1");
                trigger.getJobDataMap().put("jobMessage2","trigger信息2");
                //将触发器与任务绑定到调度器内
                scheduler.scheduleJob(jobDetail, trigger);
                log.info("任务:{}创建完成,执行时间:{},组别信息:{}",jobName,cron,group);
            }
        } catch (SchedulerException e) {
            log.error(e.getMessage());
        }
    }
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

启动类

@Slf4j
@Component
public class QuartzRunner implements CommandLineRunner {

    @Autowired
    private QuartzService quartzService;
    @Override
    public void run(String... strings) throws Exception {
        log.info("启动系统创建初始job任务");
        quartzService.createJob();
    }
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

 

  • cron表达式手动解析方式,固定年月日参数。
  • 同组job名不能相同,非同组job名可相同。 
  • jobDetail.getJobDataMap()、trigger.getJobDataMap()可传入参数到job中使用

启动项目,job随着启动类创建在RAM中,到指定cron时间执行。

quartz操作job方法

/**
     * 根据组名查询组下所有job信息
     * @param group
     * @return
     */
    public String getJobByGroup(String group) throws SchedulerException {
        Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(group));
        StringBuilder message = new StringBuilder();
        for (JobKey jobKey : jobKeys) {
            message.append(jobKey.getName() + "----------------" + jobKey.getGroup() + "\n");
        }
        return message.toString();
    }

    /**
     * 获取Job状态
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
    public String getJobState(String jobName, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);
        return scheduler.getTriggerState(triggerKey).name();
    }

    /**
     * 暂停所有任务
     * @throws SchedulerException
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暂停任务
     * @param jobName
     * @param jobGroup
     * @return
     * @throws Exception
     */
    public void pauseJob(String jobName, String jobGroup) throws Exception {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        if(!scheduler.checkExists(jobKey)){
            throw new Exception("jobKey不存在");
        }
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            throw new Exception("调度中心未查询到job信息");
        }else {
            scheduler.pauseJob(jobKey);
        }
    }

    /**
     * 恢复所有任务
     * @throws SchedulerException
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢复某个任务
     * @param jobName
     * @param jobGroup
     * @return
     * @throws Exception
     */
    public void resumeJob(String jobName, String jobGroup) throws Exception {

        JobKey jobKey = new JobKey(jobName, jobGroup);
        if(!scheduler.checkExists(jobKey)){
            throw new Exception("jobKey不存在");
        }
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            throw new Exception("调度中心未查询到job信息");
        }else {
            scheduler.resumeJob(jobKey);
        }
    }

    /**
     * 删除某个任务
     * @param jobName
     * @param jobGroup
     * @return
     * @throws Exception
     */
    public void deleteJob(String jobName, String jobGroup) throws Exception {
        JobKey jobKey = new JobKey(jobName,jobGroup);
        if(!scheduler.checkExists(jobKey)) {
            throw new Exception("jobKey不存在");
        }
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null ) {
            throw new Exception("调度中心未查询到job信息");
        }else {
            scheduler.deleteJob(jobKey);
        }
    }

    /**
     * 修改任务
     * @param quartzRequest
     * @return
     * @throws Exception
     */
    public void modifyJob(QuartzRequest quartzRequest) throws Exception {
        if (!CronExpression.isValidExpression(quartzRequest.getCron())) {
            throw new Exception("表达式格式不正确");
        }
        TriggerKey triggerKey = TriggerKey.triggerKey(quartzRequest.getJobName(),quartzRequest.getJobGroup());
        JobKey jobKey = new JobKey(quartzRequest.getJobName(),quartzRequest.getJobGroup());
        if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) {
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            //表达式调度构建器,不立即执行
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzRequest.getCron()).withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();

            //按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }else {
            throw new Exception("job or trigger not exists");
        }
    }
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

参数类QuartzRequest

@Data
public class QuartzRequest {
    @ApiModelProperty(value = "任务名称")
    private String jobName;

    @ApiModelProperty(value = "任务组")
    private String jobGroup;

    @ApiModelProperty(value = "表达式")
    private String cron;

}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

controller类 

 

@RestController
@Slf4j
@Api(value = "quartz调度器类",description = "quartz调度器类")
@RequestMapping(value = "/api/quartzController")
public class QuartzController {
    @Autowired
    private QuartzService quartzService;

    @ApiOperation(notes = "根据组名查询组下所有job信息",value = "根据组名查询组下所有job信息")
    @GetMapping("/getJobByGroup")
    public ResponseEntity<String> getJobByGroup(@RequestParam String group ){
        try {
            String jobByGroup = quartzService.getJobByGroup(group);
            return ResponseEntity.ok().body(jobByGroup);
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("获取job信息失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "根据job名和组名查询job状态",value = "根据job名和组名查询job状态")
    @GetMapping("/getJobStatus")
    public ResponseEntity<String> getJobStatus(@RequestParam String group,
                                               @RequestParam String jobName){
        try {
            String jobState = quartzService.getJobState(jobName, group);
            return ResponseEntity.ok().body(jobState);
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("获取job状态信息失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "暂停所有job任务",value = "暂停所有job任务")
    @PostMapping("/pauseAllJob")
    public ResponseEntity pauseAllJob(){
        try {
            quartzService.pauseAllJob();
            return ResponseEntity.ok().body(null);
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("暂停job信息失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "根据job名和组名暂停job任务",value = "根据job名和组名暂停job任务")
    @PostMapping("/pauseJob")
    public ResponseEntity pauseJob(@RequestParam String group,
                                   @RequestParam String jobName){
        try {
            quartzService.pauseJob(jobName,group);
            return ResponseEntity.ok().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("暂停job信息失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "恢复所有job任务",value = "恢复所有job任务")
    @PostMapping("/resumeAllJob")
    public ResponseEntity resumeAllJob(){
        try {
            quartzService.resumeAllJob();
            return ResponseEntity.ok().body(null);
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("恢复所有job任务失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "根据job名和组名恢复某个任务",value = "根据job名和组名恢复某个任务")
    @PostMapping("/resumeJob")
    public ResponseEntity resumeJob(@RequestParam String group,
                                   @RequestParam String jobName){
        try {
            quartzService.resumeJob(jobName,group);
            return ResponseEntity.ok().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("恢复某个任务失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "根据job名和组名删除某个任务",value = "根据job名和组名删除某个任务")
    @PostMapping("/deleteJob")
    public ResponseEntity deleteJob(@RequestParam String group,
                                    @RequestParam String jobName){
        try {
            quartzService.deleteJob(jobName,group);
            return ResponseEntity.ok().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除某个任务失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation(notes = "修改任务",value = "修改任务")
    @PostMapping("/modifyJob")
    public ResponseEntity modifyJob(@RequestBody QuartzRequest quartzRequest){
        try {
            quartzService.modifyJob(quartzRequest);
            return ResponseEntity.ok().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改任务任务失败:{}",e.getStackTrace());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值