美文网首页Spring Boot
Spring Boot 2.2.4基于Quartz的任务管理

Spring Boot 2.2.4基于Quartz的任务管理

作者: EasyNetCN | 来源:发表于2020-02-05 13:47 被阅读0次

    pom.xml

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

    bootstrap.yml

    spring:
      application:
        name: quartz-service
        
      profiles:
        active: development-local
      codec:
        max-in-memory-size:
          -1
      cloud:
        consul:
          host: ${consul.host:localhost}
          port: ${consul.port:8500}
          discovery:
            prefer-ip-address: true
          config:
            enabled: true
            format: yaml
            default-context: ${spring.application.name}
      cache:
        redis:
          key-prefix: ${spring.application.name}
          time-to-live: 0
      jackson:
        date-format: yyyy-MM-dd HH:mm:ss
        time-zone:
          Asia/Shanghai
      jpa:
        show-sql: false
      quartz:
        job-store-type: jdbc
        scheduler-name: sync-service
    

    多数据源情况下,定义Quartz使用的数据源

    @Bean(name = "uniondrugSyncDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.sync-service")
    @QuartzDataSource
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
    

    任务管理服务

    public class JobDetailInfo {
    
        private String jobName;
    
        private String jobGroupName;
    
        private String jobDescription;
    
        private String jobClassName;
    
        private String triggerName;
    
        private String triggerGroupName;
    
        private String triggerDescription;
    
        private String triggerCronExpression;
    
        private String jobState;
    
        private LocalDateTime startTime;
    
        private LocalDateTime endTime;
    
        private LocalDateTime finalFireTime;
    
        private LocalDateTime previousFireTime;
    
        private LocalDateTime nextFireTime;
    
        private int misfireInstruction;
    
        public String getJobName() {
            return jobName;
        }
    
        public void setJobName(String jobName) {
            this.jobName = jobName;
        }
    
        public String getJobGroupName() {
            return jobGroupName;
        }
    
        public void setJobGroupName(String jobGroupName) {
            this.jobGroupName = jobGroupName;
        }
    
        public String getJobDescription() {
            return jobDescription;
        }
    
        public void setJobDescription(String jobDescription) {
            this.jobDescription = jobDescription;
        }
    
        public String getJobClassName() {
            return jobClassName;
        }
    
        public void setJobClassName(String jobClassName) {
            this.jobClassName = jobClassName;
        }
    
        public String getTriggerName() {
            return triggerName;
        }
    
        public void setTriggerName(String triggerName) {
            this.triggerName = triggerName;
        }
    
        public String getTriggerGroupName() {
            return triggerGroupName;
        }
    
        public void setTriggerGroupName(String triggerGroupName) {
            this.triggerGroupName = triggerGroupName;
        }
    
        public String getTriggerDescription() {
            return triggerDescription;
        }
    
        public void setTriggerDescription(String triggerDescription) {
            this.triggerDescription = triggerDescription;
        }
    
        public String getTriggerCronExpression() {
            return triggerCronExpression;
        }
    
        public void setTriggerCronExpression(String triggerCronExpression) {
            this.triggerCronExpression = triggerCronExpression;
        }
    
        public String getJobState() {
            return jobState;
        }
    
        public void setJobState(String jobState) {
            this.jobState = jobState;
        }
    
        public LocalDateTime getStartTime() {
            return startTime;
        }
    
        public void setStartTime(LocalDateTime startTime) {
            this.startTime = startTime;
        }
    
        public LocalDateTime getEndTime() {
            return endTime;
        }
    
        public void setEndTime(LocalDateTime endTime) {
            this.endTime = endTime;
        }
    
        public LocalDateTime getFinalFireTime() {
            return finalFireTime;
        }
    
        public void setFinalFireTime(LocalDateTime finalFireTime) {
            this.finalFireTime = finalFireTime;
        }
    
        public LocalDateTime getPreviousFireTime() {
            return previousFireTime;
        }
    
        public void setPreviousFireTime(LocalDateTime previousFireTime) {
            this.previousFireTime = previousFireTime;
        }
    
        public LocalDateTime getNextFireTime() {
            return nextFireTime;
        }
    
        public void setNextFireTime(LocalDateTime nextFireTime) {
            this.nextFireTime = nextFireTime;
        }
    
        public int getMisfireInstruction() {
            return misfireInstruction;
        }
    
        public void setMisfireInstruction(int misfireInstruction) {
            this.misfireInstruction = misfireInstruction;
        }
    
    }
    
    public class ScheduleJob {
    
        private String jobName;
    
        private String jobGroupName;
    
        private String jobDescription;
    
        private String jobClassName;
    
        private String triggerName;
    
        private String triggerGroupName;
    
        private String triggerDescription;
    
        private String triggerCronExpression;
    
        public String getJobName() {
            return jobName;
        }
    
        public void setJobName(String jobName) {
            this.jobName = jobName;
        }
    
        public String getJobGroupName() {
            return jobGroupName;
        }
    
        public void setJobGroupName(String jobGroupName) {
            this.jobGroupName = jobGroupName;
        }
    
        public String getJobDescription() {
            return jobDescription;
        }
    
        public void setJobDescription(String jobDescription) {
            this.jobDescription = jobDescription;
        }
    
        public String getJobClassName() {
            return jobClassName;
        }
    
        public void setJobClassName(String jobClassName) {
            this.jobClassName = jobClassName;
        }
    
        public String getTriggerName() {
            return triggerName;
        }
    
        public void setTriggerName(String triggerName) {
            this.triggerName = triggerName;
        }
    
        public String getTriggerGroupName() {
            return triggerGroupName;
        }
    
        public void setTriggerGroupName(String triggerGroupName) {
            this.triggerGroupName = triggerGroupName;
        }
    
        public String getTriggerDescription() {
            return triggerDescription;
        }
    
        public void setTriggerDescription(String triggerDescription) {
            this.triggerDescription = triggerDescription;
        }
    
        public String getTriggerCronExpression() {
            return triggerCronExpression;
        }
    
        public void setTriggerCronExpression(String triggerCronExpression) {
            this.triggerCronExpression = triggerCronExpression;
        }
    
    }
    
    public interface JobService {
    
        List<JobDetailInfo> jobs() throws SchedulerException;
    
        void create(ScheduleJob scheduleJob) throws SchedulerException;
    
        void pause(String jobName, String jobGroupName) throws SchedulerException;
    
        void pauseAll() throws SchedulerException;
    
        void resume(String jobName, String jobGroupName) throws SchedulerException;
    
        void resumeAll() throws SchedulerException;
    
        void delete(String jobName, String jobGroupName) throws SchedulerException;
    
        String state(String triggerName, String triggerGroupName) throws SchedulerException;
    
        void shutdown(boolean waitForJobsToComplete) throws SchedulerException;
    }
    

    任务管理服务实现

    @Service
    public class JobServiceImpl implements JobService {
        @Autowired
        SchedulerFactoryBean schedulerFactoryBean;
    
        @Override
        public List<JobDetailInfo> jobs() throws SchedulerException {
            List<JobDetailInfo> jobDetailInfoes = new ArrayList<>();
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            GroupMatcher<JobKey> jobMatcher = GroupMatcher.anyJobGroup();
            Set<JobKey> jobKeys = scheduler.getJobKeys(jobMatcher);
    
            for (JobKey jobKey : jobKeys) {
                JobDetail jobDetail = scheduler.getJobDetail(jobKey);
                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
    
                for (Trigger trigger : triggers) {
                    JobDetailInfo jobDetailInfo = new JobDetailInfo();
    
                    jobDetailInfo.setJobName(jobKey.getName());
                    jobDetailInfo.setJobGroupName(jobKey.getGroup());
                    jobDetailInfo.setJobDescription(jobDetail.getDescription());
                    jobDetailInfo.setJobClassName(jobDetail.getJobClass().getName());
                    jobDetailInfo.setTriggerName(trigger.getKey().getName());
                    jobDetailInfo.setTriggerGroupName(trigger.getKey().getGroup());
                    jobDetailInfo.setTriggerDescription(trigger.getDescription());
    
                    CronTrigger cronTrigger = (CronTrigger) trigger;
    
                    jobDetailInfo.setTriggerCronExpression(cronTrigger.getCronExpression());
                    jobDetailInfo.setStartTime(
                            trigger.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    jobDetailInfo
                            .setEndTime(trigger.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    jobDetailInfo.setFinalFireTime(
                            trigger.getFinalFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    jobDetailInfo.setPreviousFireTime(
                            trigger.getPreviousFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    jobDetailInfo.setNextFireTime(
                            trigger.getNextFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    jobDetailInfo.setMisfireInstruction(trigger.getMisfireInstruction());
    
                    TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
    
                    jobDetailInfo.setJobState(triggerState.name());
    
                    jobDetailInfoes.add(jobDetailInfo);
                }
            }
    
            return jobDetailInfoes;
    
        }
    
        @Override
        public void create(ScheduleJob scheduleJob) throws SchedulerException {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
    
            Class<? extends Job> jobClass = null;
    
            try {
                jobClass = (Class<? extends Job>) Class.forName(scheduleJob.getJobClassName());
            } catch (ClassNotFoundException e) {
                throw new SchedulerException(e);
            }
    
            if (null != jobClass) {
                JobDetail jobDetail = JobBuilder.newJob(jobClass)
                        .withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroupName())
                        .withDescription(scheduleJob.getJobDescription()).build();
                Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity(scheduleJob.getTriggerName(), scheduleJob.getTriggerGroupName())
                        .withDescription(scheduleJob.getTriggerDescription())
                        .withSchedule(CronScheduleBuilder.cronSchedule(scheduleJob.getTriggerCronExpression())).startNow()
                        .build();
    
                scheduler.scheduleJob(jobDetail, trigger);
            }
        }
    
        @Override
        public void pause(String jobName, String jobGroupName) throws SchedulerException {
            schedulerFactoryBean.getScheduler().pauseJob(JobKey.jobKey(jobName, jobGroupName));
    
        }
    
        @Override
        public void pauseAll() throws SchedulerException {
            schedulerFactoryBean.getScheduler().pauseAll();
        }
    
        @Override
        public void resume(String jobName, String jobGroupName) throws SchedulerException {
            schedulerFactoryBean.getScheduler().resumeJob(JobKey.jobKey(jobName, jobGroupName));
        }
    
        @Override
        public void resumeAll() throws SchedulerException {
            schedulerFactoryBean.getScheduler().resumeAll();
        }
    
        @Override
        public void delete(String jobName, String jobGroupName) throws SchedulerException {
            schedulerFactoryBean.getScheduler().deleteJob(JobKey.jobKey(jobName, jobGroupName));
    
        }
    
        @Override
        public String state(String triggerName, String triggerGroupName) throws SchedulerException {
            return schedulerFactoryBean.getScheduler().getTriggerState(TriggerKey.triggerKey(triggerName, triggerGroupName))
                    .toString();
        }
    
        @Override
        public void shutdown(boolean waitForJobsToComplete) throws SchedulerException {
            schedulerFactoryBean.getScheduler().shutdown(waitForJobsToComplete);
    
        }
    
    }
    

    对外服务

    public class ShutdownParam {
        private Integer waitForJobsToComplete = 0;
    
        public Integer getWaitForJobsToComplete() {
            return waitForJobsToComplete;
        }
    
        public void setWaitForJobsToComplete(Integer waitForJobsToComplete) {
            this.waitForJobsToComplete = waitForJobsToComplete;
        }
    
    }
    
    @RestController
    @RequestMapping("jobs")
    public class JobServiceController {
        @Autowired
        JobService jobService;
    
        @GetMapping("")
        public Flux<JobDetailInfo> jobs() throws SchedulerException {
            return Flux.fromIterable(jobService.jobs());
        }
    
        @PostMapping("")
        public Mono<RestResult<Integer>> create(@RequestBody ScheduleJob scheduleJob) throws SchedulerException {
            jobService.create(scheduleJob);
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    
        @PostMapping("pause")
        public Mono<RestResult<Integer>> pause(@RequestBody ScheduleJob scheduleJob) throws SchedulerException {
            jobService.pause(scheduleJob.getJobName(), scheduleJob.getJobGroupName());
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    
        @PostMapping("pause-all")
        public Mono<RestResult<Integer>> pauseAll() throws SchedulerException {
            jobService.pauseAll();
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    
        @PostMapping("resume")
        public Mono<RestResult<Integer>> resume(@RequestBody ScheduleJob scheduleJob) throws SchedulerException {
            jobService.resume(scheduleJob.getJobName(), scheduleJob.getJobGroupName());
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    
        @PostMapping("resume-all")
        public Mono<RestResult<Integer>> resumeAll() throws SchedulerException {
            jobService.resumeAll();
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    
        @DeleteMapping("")
        public Mono<RestResult<Integer>> delete(@RequestBody ScheduleJob scheduleJob) throws SchedulerException {
            jobService.delete(scheduleJob.getJobName(), scheduleJob.getJobGroupName());
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    
        @PostMapping("state")
        public Mono<RestResult<String>> state(@RequestBody ScheduleJob scheduleJob) throws SchedulerException {
            return Mono.justOrEmpty(new RestResult<>(1, "", "",
                    jobService.state(scheduleJob.getTriggerName(), scheduleJob.getTriggerGroupName())));
        }
    
        @PostMapping("shutdown")
        public Mono<RestResult<Integer>> shutdown(@RequestBody ShutdownParam shutdownParam) throws SchedulerException {
            jobService.shutdown(shutdownParam.getWaitForJobsToComplete() == 1);
    
            return Mono.justOrEmpty(new RestResult<>(1, "", "", 1));
        }
    }
    

    相关文章

      网友评论

        本文标题:Spring Boot 2.2.4基于Quartz的任务管理

        本文链接:https://www.haomeiwen.com/subject/hkksxhtx.html