This is my second article on getting started.

One, foreword

In the previous article, “Java Scheduled Task (1)TimerTask In Principle and Practice,” we introduced one way to implement scheduled task scheduling, the Native Java TimerTask tool, which is suitable for some simple business requirements.

To review, the principle of TimerTask is summarized in the following figure:

In fact, think carefully, is it possible to abstract out a few parts?

Task scheduling, first of all, you have the task, and TimerTask is the specific task. When you have a task, do you need to set when to adjust it, how often to adjust it, and when to terminate it? This step can be called conditional setting. So what’s left is the actual execution, which is called the executor.

In fact, in terms of specific code, the latter two are the methods of the Timer

    Timer timer = new Timer();
    long delay = 0;
    long period = 1000;
    timer.schedule(timerTask, delay, period);
Copy the code

However, a serious problem with Timer is that it is single-threaded.

ScheduledExecutorService is an internal thread pool that can be used to solve the problem of abnormal Timer exits mentioned in the previous article.

A brief introduction to Quartz

Let’s follow this path to introduce a more powerful Java task scheduling framework, Quartz

Quartz has a brief introduction to the official version:

Quartz allows developers to schedule jobs based on time intervals (or days). It implements many-to-many relationships between jobs and triggers, and can associate multiple jobs with different triggers. Applications that integrate Quartz can reuse jobs from different events and can combine multiple jobs for a single event.

If you have never been involved in task scheduling, this will certainly be confusing, but I believe you will understand after reading the whole article.

Coincidentally, the design idea of Quartz is the three parts summarized above, but the name is different.

  • Job: specifies the task logic to be executed

  • Trigger: sets the Trigger condition, interval, and end time of the Job

  • Scheduler: the Scheduler starts the Trigger to execute the Job

Is this consistent with the summary of TimerTask in the preface?

Creation of the Quartz Demo

If you use the traditional way, you go to the official download a JAR package, create a New Java project, and the guide package is ok. These days, it’s common to use automated build tools.

Go to start.spring. IO/and fill in the configuration. Here I’m using Maven

You can also select Add Dependencies on the right, so I usually add the dependencies to the POM file myself.

Import dependence

	<dependency>
	    <groupId>org.quartz-scheduler</groupId>
	    <artifactId>quartz</artifactId>
	    <version>2.32.</version>
	</dependency>
Copy the code

Write a Demo

	public static void main(String[] args) {
		 try {
             // The factory method gets the default scheduler
             Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

             / / start
             scheduler.start();
             / / close
             scheduler.shutdown();

         } catch(SchedulerException se) { se.printStackTrace(); }}Copy the code

This example is provided by the website 【 www.quartz-scheduler.org/documentati… is very simple, a total of three lines of code.

What is the result of execution?

22:47:27.348 [main] INFO org.quartz.impl.StdSchedulerFactory - Using default implementation for ThreadExecutor
22:47:27.355 [main] INFO org.quartz.simpl.SimpleThreadPool - Job execution threads will use class loader of thread: main370 [22:47:27.main] INFO org.quartz.core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl370 [22:47:27.main] INFO org.quartz.core.QuartzScheduler - Quartz Scheduler vThe 2.3.2created371 [. 22:47:27.main] INFO org.quartz.simpl.RAMJobStore - RAMJobStore initialized372 [. 22:47:27.main] INFO org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v23.2) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler'-running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool'-with 10 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore'-which does not support persistence. and is not clustered372 [. 22:47:27.main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties372 [' 22:47:27.main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler version372 [22:47:27 2.3.2.main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started372 [. 22:47:27.main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down372 [. 22:47:27.main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused372 [. 22:47:27.main] DEBUG org.quartz.simpl.SimpleThreadPool - Shutting down threadpool. 372 [22:47:27.DefaultQuartzScheduler_QuartzSchedulerThread] DEBUG org.quartz.core.QuartzSchedulerThread - batch acquisition of 0 triggers372 [22:47:27.main] DEBUG org.quartz.simpl.SimpleThreadPool - Shutdown of threadpool complete372 [. 22:47:27.main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete868 [. 22:47:27.DefaultQuartzScheduler_Worker- 6]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker- 10]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker5]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker- 4]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker- 3]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down869 [. 22:47:27.DefaultQuartzScheduler_Worker- 2]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down869 [. 22:47:27.DefaultQuartzScheduler_Worker1]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker7]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker- 8]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down868 [. 22:47:27.DefaultQuartzScheduler_Worker9]DEBUG org.quartz.simpl.SimpleThreadPool - WorkerThread is shut down.

Copy the code

The output is still a lot to look at

Quartz Scheduler v2.3.2.Created, if you see that you're using RAMJobStore initialized and you see that the storage is RAMJobStore and the SimpleThreadPool at the end is a pool of threads, so there are all of them1-10   10A threadCopy the code

What do you think of when you see a thread pool?

Check out my previous article: “How to Schedule Tasks in Java (1)

What happens if I comment out the third line of code? Notice where the arrows are. The program doesn’t stop.

Here’s an explanation on the official website:

Once you obtain a scheduler using StdSchedulerFactory.getDefaultScheduler(), your application will not terminate until you call scheduler.shutdown(), because there will be active threads.

Once use StdSchedulerFactory. GetDefaultScheduler () to obtain the scheduler, the call scheduler. The shutdown () before the application will not end, because there will be active threads.

With start and stop, the specific execution of the task is naturally done in the middle.

Copy the example from the official website, and it is clear that there is an error. One reason is that there is no HelloJob class and another static import needs to be added

public class HelloJob implements Job{

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// TODO Auto-generated method stub
		
		SimpleDateFormat  simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		System.out.println("Hello! The current time is:+simpleDateFormat.format(newDate())); }}// Note that static imports are not in the HelloJob class

import static org.quartz.JobBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
Copy the code

Of course, before executing, you must add thread.sleep () in front of the stop, otherwise, it will be closed directly.

To see the effect as quickly as possible, I set the interval to 5 seconds

Effect:

Okay, so that’s a simple Demo.

More on this in a future article