1. Introduction

Recently, need to write a fixed-point automatic timing task, every day to write their own small projects before, may choose to Java’s built-in Timer class, but for a project in a company, the Timer class implements timing task can have only one background threads execute tasks, and only let the procedures in accordance with a certain frequency, and cannot be performed at specified time points. At the same time, because large projects have multiple jobs that need to be automatically executed at different time points, the single-threaded Timer cannot meet the requirements. The task scheduling framework Quartz just meets these needs. I have configured this framework in the project of the company as an intern, and learned about this Quartz when using it. The summary is as follows.

2. What is Quartz?

Quartz is another open source project in the Job Scheduling area by the OpenSymphony open source organization. Developed entirely in Java, Quartz can be used to perform timed tasks, similar to java.util.timer. But compared to Timer, Quartz adds many features: persistent jobs -- that is, keeping the state of the scheduled time; Job management - Effective management of scheduled jobs;Copy the code

Quartz consists of three modules: scheduled task Job, Trigger Trigger, Scheduler and Scheduler. The simple process is that the scheduler executes tasks based on triggers.

2.1 the Job

  • Job: indicates a scheduled task and an interface that implements service logic. The interface has only one execute method. If you want to create a task, you have to implement this interface, and execute the logic of the execute method every time the task is called.
// Predefined Job interface -- POM.xml needs to load dependent packages
public interface Job {
    void execute(JobExecutionContext var1) throws JobExecutionException;
}

// Implement the Job interface and override the execute method to write the logic to be executed into the execute function
public class TestJob implements Job {
      /** Write the operation to be executed in the execute method */
      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
          System.out.println("I can do something...");
          System.out.println(sdf.format(newDate())); }} Reference: HTTPS://juejin.im/post/5a0c08c5f265da4335624c8f

//1. Create a JodDetail instance and bind it to the Hello Job class
JobDetail jobDetail = JobBuilder.newJob(QuartzOrderReturn.class)// Define the Job class as QuartzOrderReturn, where the actual execution logic resides
                    .withIdentity(StrUtils.uuid())
                    .setJobData(jobDataMap)
                    .build();
Copy the code

2.2 the Trigger

  • Trigger: the trigger is used to define the time rules for task scheduling. There are two common quartz triggers: SimpleTrigger and CornTrigger.
  • SimpleTrigger is mainly used for simple time triggers. For example, a job starts at a specified time and executes a job repeatedly at a certain interval. The number of times can be specified at any time. SimpleTrigger, for example, doesn’t solve tasks that need to be performed at midnight every day.

// Create SimpleTrigger startTime End to indicate when the trigger first fires and when it will not fire again
 SimpleTrigger trigger = newTrigger()
                    .withIdentity("trigger"."group")
                    .startAt(startTime)
                    .endAt(end)
                    .withSchedule(
                            simpleSchedule().withIntervalInHours(
                                    executeFrequency).withRepeatCount(
                                    executeBatch)).build();
Copy the code
  • CronTrigger allows you to configure a more complex trigger schedule, a calendar-based job trigger. Using SimpleTrigger triggers requires different property supports, a lot of coding, and a lot of flexibility. CornTrigger is more flexible and can control complex trigger schedules by designing Corn expressions.

  • Corn expression: Used to configure the CornTrigger instance, a string of seven expressions describing the details of a timetable.

// Create a CornTrigger such as the one below, which is designed to trigger at 12:00 noon every day
CronTrigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule("0, 0, 12 * *?)).build();
// Add job and trigger to the schedule
scheduler.scheduleJob(jobDetail, trigger);
/ / start the scheduler
scheduler.start();

Copy the code

Mp.weixin.qq.com/s/-0kwxC2lz…



cron.qqe2.com/

2.3 the Scheduler

  • Scheduler: Each time the Scheduler executes a job, it creates a new job instance before invoking the execute method. When the call is complete, the associated job instances are released and collected by the garbage collection mechanism.
  • Scheduler can bind the Trigger to a JobDetail so that when the Trigger is triggered, the corresponding Job is executed. A Job can correspond to multiple triggers, but a Trigger can correspond to only one Job.
// Add job and trigger to the schedule
scheduler.scheduleJob(jobDetail, trigger);
/ / start the scheduler
scheduler.start();
Copy the code

// A complete instance
private void quartzOrderReturn(List<String> returnIds) {
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("returnIds", returnIds);
            //1. Create a JodDetail instance and bind it to the Hello Job class
            JobDetail jobDetail = JobBuilder.newJob(QuartzOrderReturn.class)// Define the Job class as QuartzOrderReturn, where the actual execution logic resides
                    .withIdentity(StrUtils.uuid())
                    .setJobData(jobDataMap)
                    .build();
            // 2. Define a Trigger that defines the job to be executed 10 seconds later and once
            Date startTime = new Date();
            startTime.setTime(startTime.getTime() + 10000L);
            SimpleTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(StrUtils.uuid(), HeaderNameConstants.getQuartzTrigger()).startNow()// Define names and groups
                    .startAt(startTime)
                    .withSchedule(SimpleScheduleBuilder
                            .simpleSchedule()
                            .withIntervalInSeconds(2)// Define the interval to be 2 seconds
                            .withRepeatCount(0)// Define an unlimited number of repetitions
                    )
                    .build();
            // 4. Add trigger and jobdetail to the schedule
            scheduler.scheduleJob(jobDetail, trigger);
            // 5. Start scheduler
            scheduler.start();
            // 6. The task is hibernated for 20 seconds after execution
            Thread.sleep(startTime.getTime() + 20000L);
            // 7. If the scheduled task is enabled, disable it
            if (scheduler.isStarted()) {
                scheduler.shutdown(true); }}catch(SchedulerException | InterruptedException e) { e.printStackTrace(); }}Copy the code

Chart 2.4

  • IJob: indicates a pre-implemented Job interface
  • MyJob: Implements the Job interface and writes the scheduled task logic and then execute function
  • JobDetail, as the name implies, represents information about each Job. It mainly consists of two core components, Job Task and JobData Map
  • Trigger refers to the Trigger that triggers the execution plan scheduling job according to configuration rules. It mainly includes two core components, namely SimpleTrigger and CronTrigger
  • IJobStore: indicates the task storage, which stores job and trigger information.
  • ISchedulerFactory, which stands for task scheduling factory, used to manage task scheduling IScheduler.
  • IScheduler represents a task plan. It is equivalent to a container into which specific jobs and job-related triggers can be injected to achieve task scheduling. The main commonly used method: Start — Start the execution plan Shutdowm — close the execution plan
// Run string cronParam = every 2 seconds"*/2 * * * *?"; ISchedulerFactory sf = new StdSchedulerFactory(); // Create a scheduled task ISchedulersched= sf.GetScheduler(); Job = new JobDetail("myJob"."group", typeof(MyJob)); Trigger Trigger = new CronTrigger("myTrigger"."group",cronParam); Sched.schedulejob (job, trigger); // Start the scheduled task sched.start (); // Shutdown the scheduled task // sched.shutdown ();Copy the code

www.cnblogs.com/wangjiming/…

3. How to implement and schedule scheduled tasks: TimeWheel

Timing is generally realized by using the time wheel algorithm. In a nutshell, the time wheel algorithm can be shown in the following figure. Its main body is a cyclic list.


Refer to the link: www.zhihu.com/question/41… www.kafka.cc/archives/24…

4. Extensions in the project

1. Encapsulate the Job class

2. Manage multiple scheduled tasks on the page

5. To summarize

  • Understanding what Quartz is and what parts does it involve?
  • Understand how Quartz implements timed tasks?
  • Understand how Quartz manages scheduling multiple scheduled tasks?
  • What extensions could be made to actually use Quartz in the project?