springboot整合quartz实现手动控制任务启动,暂停,重启

Maven依赖

 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-quartzartifactId>
            <version>2.5.4version>
 dependency>

Job

public class Job1 extends QuartzJobBean {


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        StringJoiner outStr=new StringJoiner(" | ")
                .add("Job1")
                .add(Thread.currentThread().getName())
                .add(context.getTrigger().getKey().getName());
        System.out.println(outStr);
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String somethingToUse = jobDataMap.getString("somethingToUse");
        System.out.println(somethingToUse);
    }

JobService

@Service
public class JobService {

    @Autowired
    Scheduler scheduler;

   static TriggerKey task1 = new TriggerKey("task1");


    public void startOrResumeJob(String somethingToUse) throws SchedulerException {


        if (scheduler.getTriggerState(task1).toString()=="PAUSED") {
            scheduler.resumeTrigger(task1);
        }else{
            JobDetail jobDetail = JobBuilder
                    .newJob(Job1.class)
                    .usingJobData("somethingToUse",somethingToUse)
                    .build();

            Trigger trigger= TriggerBuilder.newTrigger()
                    .withIdentity(task1)
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                    .build();
            scheduler.scheduleJob(jobDetail,trigger);
        }


    }

    public void pauseJob() throws SchedulerException{
        scheduler.pauseTrigger(task1);

    }
}

Controller

@RestController
@RequestMapping("job")
public class JobController {
    @Autowired
    JobService jobService;

    @GetMapping("start")
    public String start(String somethingToUse){
        try {
            jobService.startOrResumeJob(somethingToUse);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return "fail";
        } return "SUCCESS";
    }


    @RequestMapping("pause")
    public String pause(){
        try {
            jobService.pauseJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
            return "fail";
        } return "succesToPause";

    }
}

你可能感兴趣的:(Quartz,quartz,spring)