Summary of using Quartz task scheduling timer

I. Preface

Quartz is an open source job scheduling framework written entirely in java. In human words, you can create some tasks, specify when and how many times they are executed. This article documents the common methods used by quartz in the project process.
Official download address http://www.quartz-scheduler.org/downloads/
The official website is slow and can be downloaded in CSDN https://download.csdn.net/download/leytton/10346005
After testing, you only need to introduce quartz-2.2.3.jar, quartz-jobs-2.2.3.jar and slf4j-api-1.7.7.jar
Or use Maven:

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
  </dependency>
  <dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.1</version>
  </dependency>

2, Quartz project structure

Reference resources https://www.cnblogs.com/drift-ice/p/3817269.html

0x01. Define a task

JobHelloQuartz.java

public class JobHelloQuartz implements Job {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail detail = context.getJobDetail();
        String name = detail.getJobDataMap().getString("name");
        System.out.println(detail.getKey()+" say hello to " + name + " at " + sdf.format(new Date()));
    }
}

0x02 schedule task

Test01.java

public class Test01 {

    public static void main(String[] args) {

        try {
            // Create a scheduler
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            // Define a Trigger
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("Trigger_HelloQuartz", "group1") // Define name/group
                    // . startNow() / / once the scheduler is added, execute immediately
                    .startAt(new Date(System.currentTimeMillis() + 5000))// Execute in 5 seconds
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule() // Using SimpleTrigger
                            .withIntervalInSeconds(2) // Every 2 seconds
                            .withRepeatCount(1))// Repeat once, 2 times in total
                            // . repeatForever()) / / execute all the time and keep running till the end
                    .build();

            // Define a JobDetail
            JobDetail job = JobBuilder.newJob(JobHelloQuartz.class) // Define Job class as JobHelloQuartz
                    .withIdentity("helloJob", "group1") // Define name/group
                    .usingJobData("name", "Leytton") // Defining attributes
                    .build();

            // Join this schedule
            scheduler.scheduleJob(job, trigger);

            // Starting up
            scheduler.start();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            System.out.println("Quartz start at " + sdf.format(new Date()));
            // Close after running for a period of time
            // Thread.sleep(10000);
            // scheduler.shutdown(true);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Log output

Quartz start at 2018-04-13 11:38:26
group1.helloJob say hello to Leytton at 2018-04-13 11:38:31
group1.helloJob say hello to Leytton at 2018-04-13 11:38:33

If. Startat is defined (new date (system. Currenttimemillis() - 5000))
//Execute 5 seconds ago, once in 2 seconds, twice in total, then the program will be executed twice at a time when it is started

Quartz start at 2018-04-13 11:50:08
group1.helloJob say hello to Leytton at 2018-04-13 11:50:08
group1.helloJob say hello to Leytton at 2018-04-13 11:50:08

If it is executed once in 4 seconds, it will be executed twice when the program starts

.withIntervalInSeconds(4)

If it is executed once in 6 seconds, it will be executed once when the program is started, and once again in 1 second

.withIntervalInSeconds(6)
Quartz start at 2018-04-13 11:53:21
group1.helloJob say hello to Leytton at 2018-04-13 11:53:21
group1.helloJob say hello to Leytton at 2018-04-13 11:53:22

3, Use cases

0x01 once a day

This situation should be the most common. Most of the timing tasks currently used are of this type
The following is executed at 4 a.m. every day

Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

//Daily4Point execution BEGIN################################
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 4);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
//If the time of the day has passed, arrange to start the next day, otherwise it will be executed immediately
//if(System.currentTimeMillis()>cal.getTimeInMillis()) {
//  cal.add(Calendar.DAY_OF_YEAR, 1);
//}
Date startTime=cal.getTime();

Trigger trigger_xx = TriggerBuilder.newTrigger().withIdentity("trigger_xx", "group1")
        .startAt(startTime)
        .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule()
            .withIntervalInDays(1))
        .build();

JobDetail job_xx = JobBuilder.newJob(Job_xx.class)
    .withIdentity("job_xx", "job_group1")
    .build();

scheduler.scheduleJob(job_xx, trigger_xx);
scheduler.start();

Once every N days
.withIntervalInDays(N))

Tags: Java Maven

Posted on Sun, 05 Apr 2020 17:07:54 -0700 by wertz33