Configuring Quartz scheduled tasks with Spring Boot

Quartz has four core concepts:

Job: it is an interface. Only one method execute (jobexecutioncontext) is defined. The job (task) that needs to be executed regularly is written in the execute method that implements the interface
Double slongitude = Double.valueOf(jobExecutionContext.getJobDetail().getJobDataMap().get("slongitude").toString());
JobDetail: every time Quartz schedules a Job, it recreates a Job instance. Therefore, it does not accept an instance of a Job. Instead, it receives a Job implementation class (JobDetail, which describes the implementation class of the Job and other related static information, such as Job name, description, associated listener and so on), so that the Job can be instantiated at runtime through the reflection mechanism of newInstance().
rigger: it is a class that describes the time trigger rules that trigger Job execution, mainly including SimpleTrigger and CronTrigger. SimpleTrigger is the most suitable choice when and only when scheduling is required once or scheduling is performed periodically at fixed time intervals; CronTrigger can define various scheduling schemes of complex time rules through Cron expression, such as scheduling from 15:00 to 16:00 from Monday to Friday.
Scheduler: the scheduler is equivalent to a container loaded with tasks and triggers. This class is an interface that represents an independent running container of Quartz. Trigger and JobDetail can be registered in the scheduler. They have their own groups and names in the scheduler. The groups and names are the basis for the scheduler to find and locate an object in the container, Trigger's group and name must be unique, and JobDetail's group and name must also be unique (but they can be the same as trigger's group and name because they are different types). The scheduler defines multiple interface methods that allow external users to access and control trigger and JobDetail in the container through groups and names.

1. Import pom dependency

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

2. Start scheduled task

@Enableshcheduling annotation

//java fhadmin.cn
@EnableScheduling
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

3. Create a new job

@Slf4j
public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {

            executeTask(jobExecutionContext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //java fhadmin.cn
    private static void executeTask(JobExecutionContext jobExecutionContext) throws SchedulerException {
//The JobExecutionContext class provides some information for scheduling applications;
//The Job runtime information is saved in the JobDataMap instance.

        JobKey key = jobExecutionContext.getJobDetail().getKey();
        System.out.println(new Date()+"->"+key.toString()+"Scheduled task in progress");

    }

}

4. Build JobDetail rigger and register Trigger and JobDetail in Scheduler

//fhrom fhadmin.cn
@Configuration
public class QuartzManager {

   // public static final String JOB1="job1";
   // public static final String GROUP1="group1";
    /**It is executed at 1 a.m. every week by default*/
    //public static final String DEFAULT_CRON="0 0 1 ? * L";
    /**The default is once every 5 seconds*/
   // public static final String DEFAULT_CRON="*/5 * * * * ?";

    /**
     * task scheduling 
     */

     private Scheduler scheduler;

     @Bean
    public Scheduler scheduler() throws SchedulerException {
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        this.scheduler = schedulerFactoryBean.getScheduler();
        return schedulerFactoryBean.getScheduler();
    }
    /**
     * Start scheduled task
     */
    public void startJob(String name,String group,String time) throws SchedulerException {
        startJobTask(scheduler,name,group,time);
        scheduler.start();
    }
    /**
     * Start scheduled task
     * @param scheduler
     */
    private void startJobTask(Scheduler scheduler,String  name ,String group,String time) throws SchedulerException {
                                                           //For identity
        JobDetail jobDetail= JobBuilder.newJob(MyJob.class).withIdentity(name,group).build();
        System.out.println("jobDetail:-------------"+jobDetail);

        String DEFAULT_CRON="*/"+time+" * * * * ?";
        // Simpleschedulebuilder cronschedulebuilder is used to build a Scheduler and define the time rules for task scheduling
        CronScheduleBuilder cronScheduleBuilder=CronScheduleBuilder.cronSchedule(DEFAULT_CRON);
        //trigger
        CronTrigger cronTrigger=TriggerBuilder.newTrigger().withIdentity(name,group)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);

    }

    /**
     * Get Job information
     * @param name
     * @param group
     */
    public String getjobInfo(String name,String group) throws SchedulerException {
        TriggerKey triggerKey=new TriggerKey(name,group);
        System.out.println("triggerKey:"+triggerKey);
        CronTrigger cronTrigger= (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s",cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * Modify the execution time of the task
     * @param name
     * @param group
     * @param cron cron expression
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(String name,String group,String cron) throws SchedulerException{
        Date date=null;
        TriggerKey triggerKey=new TriggerKey(name, group);
        CronTrigger cronTrigger= (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime=cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(cron)){
            CronScheduleBuilder cronScheduleBuilder=CronScheduleBuilder.cronSchedule(cron);
            CronTrigger trigger=TriggerBuilder.newTrigger().withIdentity(name,group)
                    .withSchedule(cronScheduleBuilder).build();
            date=scheduler.rescheduleJob(triggerKey,trigger);
        }
        return date !=null;
    }

    /**
     * Pause all tasks
     * @throws SchedulerException
     */
    public void pauseAllJob()throws SchedulerException{
        scheduler.pauseAll();
    }

    /**
     * Pause a task
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name,String group)throws SchedulerException{
        JobKey jobKey=new JobKey(name,group);
        JobDetail jobDetail=scheduler.getJobDetail(jobKey);
        if (jobDetail==null) {
            return;
        }
        scheduler.pauseJob(jobKey);
    }

    /**
     * Restore all tasks
     * @throws SchedulerException
     */
    public void resumeAllJob()throws SchedulerException{
        scheduler.resumeAll();
    }
    /**
     * Resume a task
     */
    public void resumeJob(String name,String group)throws SchedulerException {
        JobKey jobKey=new JobKey(name,group);
        JobDetail jobDetail=scheduler.getJobDetail(jobKey);
        if (jobDetail==null) {
            return;
        }
        scheduler.resumeJob(jobKey);
    }

    /**
     * Delete a task
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name,String group)throws SchedulerException{
        JobKey jobKey=new JobKey(name, group);
        JobDetail jobDetail=scheduler.getJobDetail(jobKey);
        if (jobDetail==null) {
            return;
        }
        scheduler.deleteJob(jobKey);
    }

}

5. Write Controller

By calling the interface, you can start a scheduled task and end a scheduled task to obtain task information

//fhadmin.cn
@RestController
@RequestMapping("/quartz")
public class ModifyCronController {

    @Autowired
    private QuartzManager quartzManager;
    @GetMapping("/modify")
    public String modify(@RequestParam("job")String job,   //The name of the job
                         @RequestParam("group")String group,//job group
                         @RequestParam("time")String time   //Step size for executing scheduled tasks
     ) throws SchedulerException {

       // quartzManager.pauseJob(QuartzManager.JOB1,QuartzManager.GROUP1);
        quartzManager.startJob(job,group,time);
        String s = quartzManager.getjobInfo(job, group);
        System.out.println("job:"+s);

        return "ok";
    }
}

Tags: Java Spring Boot

Posted on Wed, 08 Sep 2021 00:34:40 -0400 by Malkavbug