Spring Boot integrates Quarz to realize automatic triggering of scheduled tasks

foreword

Use Quartz to implement a configurable timing task, and write the timing task Quartz to the database. Now I want to automatically trigger the scheduled task as the project starts, the following is the implementation method:

Project self-start

Spring Boot uses ApplicationRunner to implement business operations directly after project startup.

This blog describes in detail the implementation of automatic business operations after project startup. We only need to add the method interface called by the scheduled task in the run method.

		log.info("启动定时任务");
        quartzService.startQuartz();

Scheduled task start

Obtain scheduled task information from the database

	public void startQuartz(){
    
    
        String jobGroup ="MySyncTask";
        String jobName ="定时人数";
        try {
    
    
            //先已有的任务
            List<Quartz> list = quartzMapper.findList(jobGroup, jobName);
            if(list != null && list.size()>0){
    
    
                log.info("项目启动后,启动定时任务:{}",list.get(0).getJobName());
                doQuatrz(list.get(0));
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
            log.error("项目启动后,启动定时任务发生异常:{}",e.getMessage());
            API.e("项目启动后,启动定时任务发生异常");
        }
    }

Timed task query and trigger

	private void doQuatrz(Quartz quartz){
    
    
        try {
    
    
            //直接启动
            Class cls = Class.forName(quartz.getJobClassName()) ;
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),quartz.getJobGroup()).withDescription(quartz.getDescription()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger_"+quartz.getJobName(), quartz.getJobGroup()).withDescription(quartz.getDescription()).startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
            quartz.setJobStatus(JobStatus.RUN.getStatus());
            quartzRepository.save(quartz);
        }catch (Exception e){
    
    
            e.printStackTrace();
            log.error("执行任务发生异常:{}",e.getMessage());
            API.e("执行任务发生异常");
        }
    }

Guess you like

Origin blog.csdn.net/qq_28545605/article/details/125726572