亲宝软件园·资讯

展开

SpringBoot Quartz动态定时任务

你是我的小丫小太阳 人气:0

目前常用的几种任务调度

SpringBoot项目的实现方法

1.config配置

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
 
import java.io.IOException;
import java.util.Properties;
 
/**
 * quartz配置
 */
@Configuration
public class SchedulerConfig {
    
    @Bean(name="SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setAutoStartup(true);
        //factory.setStartupDelay(5);//延时5秒启动
        return factory;
    }
 
    /*
     * quartz初始化监听器
     */
    @Bean
    public QuartzInitializerListener executorListener() {
       return new QuartzInitializerListener();
    }
 
    /*
     * 通过SchedulerFactoryBean获取Scheduler的实例
     */
    @Bean(name="Scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }
 
}

2.实现方法

/**
     * 新建任务
     * **/
    @ApiOperation(value = "Test-add", notes = "Test-add")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cruiseId", value = "巡航线id", required = true, paramType = "path"),
            @ApiImplicitParam(name = "jobName", value = "任务名称", required = true, paramType = "query"),
            @ApiImplicitParam(name = "jobGroup", value = "任务分组", required = true, paramType = "query"),
            @ApiImplicitParam(name = "executeDate", value = "当前时间[yyyy-MM-dd HH:mm:ss]", required = true, paramType = "query", dataType = "Date")})
    @PutMapping("/test/add/{cruiseId}")
    public ResultBody test(@PathVariable("cruiseId") String cruiseId,@RequestParam("jobName") String jobName,@RequestParam("jobGroup") String jobGroup,
                           @RequestParam(value = "executeDate")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date executeDate) {
        try {
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //构建job信息
            JobDetail job = JobBuilder.newJob(CruisePlanJob.class).withIdentity(jobName, jobGroup)
                            .withDescription("巡航计划").build();
            JobDataMap jobDataMap = job.getJobDataMap();
            jobDataMap.put("cruiseId", cruiseId);
            //CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("cron的表达式");
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger" + jobName, jobGroup)
                    .startAt(executeDate)
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                    .build();
            //SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0).withIntervalInSeconds(20)//每隔多少秒执行一次; withRepeatCount 设置重复的次数
            //.startNow().withSchedule(cronScheduleBuilder)
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
            System.out.println("startJob:"+JobKey.jobKey(jobName));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.failed();
        }
        return ResultBody.ok();
    }
 
    /**
     * 删除任务
     * **/
    @ApiOperation(value = "Test-remove", notes = "Test-remove")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobName", value = "任务名称", required = true, paramType = "query"),
            @ApiImplicitParam(name = "jobGroup", value = "任务分组", required = true, paramType = "query")})
    @GetMapping("/test/remove")
    public ResultBody remove(@RequestParam("jobName") String jobName,@RequestParam("jobGroup") String jobGroup) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            boolean result = scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));
            System.out.println(result);
            System.out.println("removeJob:"+JobKey.jobKey(jobName));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.failed();
        }
        return ResultBody.ok();
    }

3.CruisePlanJob类实现具体逻辑

@Slf4j
public class CruisePlanJob implements Job {
 
  @Override
  public void execute(JobExecutionContext context) {
    try{
      JobDataMap jdMap = context.getJobDetail().getJobDataMap();
      String cruiseId = (String) jdMap.get("cruiseId");
      String panId = (String) jdMap.get("panId");
      String userId = (String) jdMap.get("userId");
      String appId = (String) jdMap.get("appId");
      //TODO 逻辑待补充
 
      log.info("cruisePlan-CruisePlanJob-计划执行开始===>panId:{}---cruiseId:{}---appId:{}---userId:{}---resultBody:{}", panId, cruiseId,  appId,  userId, resultBody);
    }catch (Exception e){
      e.printStackTrace();
    }
  }
 
}

4.另外两种任务的方法

//恢复任务  
scheduler.resumeJob(key);
//停止任务
scheduler.pauseJob(key);

加载全部内容

相关教程
猜你喜欢
用户评论