Task scheduling: Quartz

1. Quartz example

public class JobTest implements Job {

    /**
     * Specific tasks
     *
     * @param jobExecutionContext Save some information about the job runtime
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        //Reference to scheduler to execute job
        Scheduler scheduler = jobExecutionContext.getScheduler();
        //Reference to trigger that triggers job
        Trigger trigger = jobExecutionContext.getTrigger();
        //JobDetail object references, and some other information
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        //Get parameters
        //JobDataMap in JobExecution Context: He is the union of JobDataMap in JobDetail and JobDataMap in Trigger
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        Object jobDetailValue = jobDataMap.get("jobDetailKey");
        Object simpleTriggerValue = jobDataMap.get("simpleTriggerKey");
        Object cronTriggerValue = jobDataMap.get("cronTriggerKey");
        //Details of mission implementation
        String key = "jobDetailValue:" + jobDetailValue + " simpleTriggerValue:" + simpleTriggerValue + " cronTriggerValue:" + cronTriggerValue;
        System.err.println(new Date() + ": doing something...Acquired key:" + key);
    }
}

class QuartzTest {
    public static void main(String[] args) throws Exception {
        //1. Create JobDetial objects
//        Every time a scheduler executes a job, it calls its execute(... ) A new instance of the JobTest class is created before the method
        JobDetail jobDetail = JobBuilder.newJob(JobTest.class)
                //Setting the grouping and name of JobDetial
                .usingJobData("jobDetailKey", "jobDetailValue")
                .withIdentity("job1", "group1")
                .build();

        //2. Creating Trigger Objects: SimpleTrigger
        Trigger simpleTrigger = newTrigger()
                //Set the grouping and name of the trigger
                .withIdentity("simpleTrigger", "simpleTriggerGroup")
                //start time
                .startAt(new Date())
                //End time
                .endAt(new Date())
                //set priority
                .withPriority(1)
                //Setting parameters
                .usingJobData("simpleTriggerKey", "simpleTriggerValue")
                .withSchedule(simpleSchedule()
                        //Execute every other second
                        .withIntervalInSeconds(1)
                        //Always execute
                        .repeatForever())
                .build();

        //Create a Trigger object: CronTrigger
        CronTrigger cronTrigger = newTrigger()
                .usingJobData("cronTriggerKey", "cronTriggerValue")
                .withIdentity("cronTrigger", "cronTriggerGroup")
                .withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?"))
                //set priority
                .withPriority(1)
                .build();

        //3. Create a scheduler: Scheduler
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        //Configure JobDetail and Trigger objects
        scheduler.scheduleJob(jobDetail, cronTrigger);
        //4. Start and close
        scheduler.start();
        Thread.sleep(10000);

        //Close scheduler: Wait for job execution to complete before closing
        scheduler.shutdown(true);
        System.err.println("-------Turn off the scheduler-------");

    }
}

Task example: JobDetail

A specific executable scheduler. Includes, name, grouping, job class, JobDataMap. Through JobBuilder. build() method creation

Every time a scheduler executes JobDetail, an instance of job's class (TestJob) is created and its execute(... ) Method performs the task; after execution, the reference to the instance is discarded.

Trigger: Trigger

According to the rules, frequency and other dimensions (cron expression) to perform tasks.

There are two common types: simple Trigger and Ron Trigger. Create by triggerBuilder.build()

Scheduler: Scheduler

Manage all JobDetail and Trigger containers. Responsible for managing thread pool, thread scheduling to perform tasks.

StdScheduler Factory (commonly used) and getScheduler() creation of DirectScheduler Factory

Task: Job

Represents the specific content of a work to be performed. There is only one method in this interface

public interface Job {
    void execute(JobExecutionContext var1) throws JobExecutionException;
}

Quartz is huge, but everything revolves around these components.

2. springboot integration quartz

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
//Configuration class
@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail initTaskDetail() {
        return JobBuilder.newJob(InitCompanyTask.class).withIdentity("InitCompanyTask").storeDurably().build();
    }

    @Bean
    public Trigger initTaskTrigger() {
        CronTrigger cronTrigger = newTrigger()
                .forJob(initTaskDetail())
//                .usingJobData("cronTriggerKey", "cronTriggerValue")
                .withIdentity("InitCompanyTask")
                .withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?"))
                //set priority
                .withPriority(1)
                .build();
        return cronTrigger;
    }
}
//Task class
public class InitCompanyTask extends QuartzJobBean {

    private static final Logger logger = LoggerFactory.getLogger(InitCompanyTask.class);

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //Perform tasks
    }

}

 

 

Tags: SpringBoot Spring

Posted on Mon, 07 Oct 2019 05:50:14 -0700 by Natty_Dreadlock