Basic use of the timed task framework Quartz

1. Scenario of scheduled tasks

Timing task form: Execute every certain time/at a specific time.

For example:

  • Regular backup data
  • Daily settlement of the financial system
  • Data archiving, cleaning jobs
  • Reports, offline data analysis jobs
  • Order review, delivery
  • Order overtime automatic cancellation, payment refund
  • ........

2. The difference between scheduled tasks and message queues

common ground

        asynchronous processing

         Such as registration and order events

        Application decoupling

        Regardless of the scheduled task job or MQ, it can be used as a wheel between two applications to achieve application decoupling. This wheel can transfer data. Of course, this does not need to be considered for a single service, which is often considered when splitting a service.

        flow clipping

        During Double Eleven, both task operations and MQ can be used to carry traffic. The back-end system processes orders at regular intervals according to service capabilities or triggers processing when an order arrival event is captured from MQ. For front-end users It is said that the result seen is that the order has been placed successfully, and the order will not be affected in any way.

Essentially different

  • Scheduled task jobs are time-driven, while MQ is event-driven;
  • Time-driven is irreplaceable. For example, the daily interest settlement of the financial system does not mean that the interest is calculated once (interest arrival event), but is often calculated in batches through timed tasks;
  • Therefore, scheduled task jobs are more inclined to batch processing, and MQ tends to be processed one by one;

3. Implementation of scheduled tasks

There are many ways to implement scheduled tasks. When there was no timing task framework in the early days, the Timer mechanism and multi-threading system (Runnable+thread sleep) in JDK were used to implement timing or to execute a certain program at intervals; later, there was a timing task framework, such as large The well-known Quartz task scheduling framework uses time expressions (including: seconds, minutes, hours, days, weeks, and years) to configure when a certain task will be executed.

        1. Import jar

        <!--任务调度框架quartz-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
        </dependency>

        2. Write the timing task main scheduler

package com.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzMain {

    // 创建作业任务调度器
    public static Scheduler createScheduler() throws
            SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        return scheduler;
    }


    // 创建⼀个作业任务
    public static JobDetail createJob() {
        JobBuilder jobBuilder = JobBuilder.newJob(DemoJob.class);
        jobBuilder.withIdentity("jobName", "myJob");
        JobDetail jobDetail = jobBuilder.build();
        return jobDetail;
    }

    /**
     * 创建作业任务时间触发器(
     * cron表达式由七个位置组成,空格分隔
     * 1、Seconds(秒) 0~59
     * 2、Minutes(分) 0~59
     * 3、Hours(⼩时) 0~23
     * 4、Day of Month(天)1~31,注意有的⽉份不⾜31天
     * 5、Month(⽉) 0~11,或者 JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC
     * 6、Day of Week(周) 1~7,1=SUN或者 SUN,MON,TUE,WEB,THU,FRI,SAT
     * 7、Year(年)1970~2099 可选项
     * *示例:
     *  0 0 11 * * ? 每天的11点触发执⾏⼀次
     *  0 30 10 1 * ? 每⽉1号上午10点半触发执⾏⼀次
     */

    public static Trigger createTrigger() {
        // 创建时间触发器,按⽇历调度
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("triggerName", "myTrigger")
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?"))
                .build();
       /* // 创建触发器,按简单间隔调度
        SimpleTrigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity("triggerName", "myTrigger")
                .startNow()
                .withSchedule(SimpleScheduleBuilder
                        .simpleSchedule()
                        .withIntervalInSeconds(3)
                        .repeatForever())
                .build();*/
        return trigger;
    }

    // 定时任务作业主调度程序
    public static void main(String[] args) throws SchedulerException {
        // 1.创建⼀个作业任务调度器
        Scheduler scheduler = QuartzMain.createScheduler();
        // 2.创建⼀个作业任务
        JobDetail job = QuartzMain.createJob();
        // 3.创建⼀个作业任务时间触发器(
        Trigger trigger = QuartzMain.createTrigger();
        // 4.使⽤调度器按照时间触发器执⾏这个作业任务
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    }
}

        3. To define a job, the Job interface needs to be implemented

package com.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class DemoJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("我是⼀个定时任务逻辑");
    }
}

        4. Start the main method for testing

It is found that the timing task is executed once every 2 seconds, and the simple timing task is completed.

Summarize:

The use of timed tasks can be roughly divided into the following four steps

  • Create a job task scheduler
  • Create a job task
  • Create a job task time trigger
  • Use the scheduler to execute this job task according to the time trigger

Guess you like

Origin blog.csdn.net/xiaozhang_man/article/details/121881751