Home  >  Article  >  Java  >  Several ways of java timer

Several ways of java timer

高洛峰
高洛峰Original
2016-12-16 13:19:061437browse

quartz

spring

spring-task

Timing task

Notes

Several implementations of Spring timing tasks

Recently, some timing tasks need to be performed during project development, such as analysis in the early morning every day I took this opportunity to sort out several ways to implement scheduled tasks. Since the project uses the spring framework, I will introduce them in conjunction with the

spring framework.

1. Classification

From the perspective of implementation technology, there are currently three main technologies (or three products):

Java’s own java.util.Timer class, this class allows you to schedule a java.util.TimerTask task . Using this method allows your program to be executed at a certain frequency, but not at a specified time. Generally used less, this article will not introduce it in detail.

Use Quartz, which is a relatively powerful scheduler that allows your program to be executed at a specified time or at a certain frequency. The configuration is a bit complicated and will be introduced in detail later.

The tasks that come with Spring 3.0 and later can be regarded as a lightweight Quartz, and it is much simpler to use than Quartz, which will be introduced later.

In terms of inheritance method of job class, it can be divided into two categories:

Job class needs to inherit from a specific job class base class, such as Quartz needs to inherit from org.springframework.scheduling.quartz.QuartzJobBean; java .util.Timer needs to inherit from java.util.TimerTask.

The job class is an ordinary java class and does not need to inherit from any base class.

Note: I personally recommend using the second method, because all the classes are common classes and do not need to be treated differently in advance.

From the triggering timing of task scheduling, here are mainly the triggers used for jobs, there are mainly the following two types:

Trigger once every specified time, the corresponding trigger in Quartz It is: org.springframework.scheduling.quartz.SimpleTriggerBean

It triggers once every specified time. The corresponding scheduler in Quartz is: org.springframework.scheduling.quartz.CronTriggerBean

Note: Not every task is Both triggers can be used. For example, the java.util.TimerTask task can only use the first one. Both Quartz and spring task can support these two trigger conditions.

II. Usage instructions

Introduces in detail how to use each task scheduling tool, including Quartz and spring task.

Quartz

The first type, the job class inherits from a specific base class: org.springframework.scheduling.quartz.QuartzJobBean.

Step one: Define the job class

Java code

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.springframework.s scheduling.quartz.QuartzJobBean;

public class Job1 extends QuartzJobBean {

private int timeout;

private static int i = 0;

//After the scheduling factory is instantiated, the scheduling starts after the timeout time

public void setTimeout(int timeout) {

this.timeout = timeout;

}

/**

* Specific tasks to be scheduled

*/

@Override

protected void executeInternal(JobExecutionContext context)

throws JobExecutionException {

System. out.println( "The scheduled task is being executed...");

}

}

Step 2: Configure the job class JobDetailBean in the spring configuration file

Xml code

Description: org.springframework.scheduling .quartz.JobDetailBean has two attributes. The jobClass attribute is the task class we defined in the java code, and the jobDataAsMap attribute is the attribute value that needs to be injected into the task class.

Step 3: Configure the triggering method (trigger) of job scheduling

Quartz has two job triggers, namely

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

The first SimpleTriggerBean only supports calling tasks at a certain frequency, such as running once every 30 minutes.

The configuration method is as follows:

Xml code

th Two types of CronTriggerBean support running once at a specified time, such as once every day at 12:00.

The configuration method is as follows:

Xml code

Please refer to the appendix for the syntax of cronExpression expression.

Step 4: Configure the scheduling factory

Xml code

< ;list>

Description: This parameter specifies the previous configuration The name of the trigger.

Step 5: Just start your application, that is, deploy the project to tomcat or other containers.

Second, the job class does not inherit a specific base class.

Spring can support this approach thanks to two classes:

org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBe an

these two The classes respectively correspond to the two methods of task scheduling supported by spring, namely the timer task method and the Quartz method that come with Java as mentioned above. Here I only write about the usage of MethodInvokingJobDetailFactoryBean. The advantage of using this class is that our task class no longer needs to inherit from any class, but is an ordinary pojo.

Step 1: Write task class

Java code

public class Job2 {

public void doJob2() {

System.out.println("Does not inherit QuartzJobBean method - scheduling in progress..." );

}

}

As you can see, this is an ordinary class and has a method.

Step 2: Configure job class

Xml code

class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

< property name="concurrent" value="false" />

Description: This step is a critical step, declare a MethodInvokingJobDetailFactoryBean, There are two key attributes: targetObject specifies the task class, and targetMethod specifies the method to run. The following steps are the same as method 1. For the sake of completeness, they are also posted.

Step 3: Configure the triggering method (trigger) of job scheduling

Quartz has two job triggers, namely

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

The first SimpleTriggerBean only supports calling tasks at a certain frequency, such as running once every 30 minutes.

The configuration method is as follows:

Xml code

The second CronTriggerBean supports running once at a specified time, such as It runs once a day at 12:00 and so on.

The configuration method is as follows:

Xml code

The above two scheduling methods are based on actual conditions , choose any one.

Step 4: Configure the scheduling factory

Xml code

< ;list>

The name of the trigger.

Step 5: Just start your application, that is, deploy the project to tomcat or other containers.

At this point, the basic configuration of Quartz in spring has been introduced. Of course, before using it, you need to import the corresponding spring package and Quartz package. Needless to say these.

In fact, it can be seen that the configuration of Quartz seems quite complicated. There is no way, because Quartz is actually a heavyweight tool. If we just want to simply execute a few simple scheduled tasks, is there a simpler tool? ,have!

Please see my introduction to Spring task below.

Spring-Task

The previous section introduced the use of Quartz in Spring. This article introduces the self-developed scheduled task tool after Spring 3.0, spring task, which can be compared to a lightweight Quartz , and it is very simple to use. No additional packages are required except spring-related packages, and it supports two forms of annotations and configuration files. These two methods will be introduced below.

The first one: Configuration file method

The first step: Write the job class

That is, the ordinary pojo, as follows:

Java code

import org.springframework.stereotype.Service;

@Service

public class TaskJob {

                                                                                   public void job1() {                                                                                                                                                       Step 2: In spring Add namespace and description to the configuration file header

Xml code

xmlns:task="http://www.springframework. org/schema/task"

. . . . . .

xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

Third Step: Set specific tasks in the spring configuration file

Xml code

                                                                               "/> That is, the task class. The method specified by method is the method that needs to be run, cron and cronExpression expressions. The specific writing method is not introduced here. For details, see the appendix of the previous article.

Needless to say, this configuration is used for spring scanning annotations.

The configuration is complete here, isn’t it very simple?

Second: Use annotation form

Maybe we don’t want to configure it in the xml file every time we write a task class. We can use the annotation @Scheduled. Let’s take a look at the definition of this annotation in the source file:

Java code

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Scheduled

{

public abstract String cron();

public abstract long fixedDelay();

public abstract long fixedRate(); , the respective meanings are:

cron: Specify the cron expression

fixedDelay: Official document explanation: An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds. That means the interval from the completion of the previous task to the start of the next task , the unit is milliseconds.

fixedRate: Official document explanation: An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds. That is, from the start of the previous task to the start of the next task Interval in milliseconds.

Now let me configure it.

Step one: Write pojo

Java code

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component("taskJob")

public class TaskJob {

@Scheduled(cron = "0 0 3 * * ?")

public void job1() {

System.out.println("Task in progress...");

}

}

Step 2: Add task-related configuration:

Xml code

​ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework. org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:task="http://www.springframework.org/schema/task"

/schema/beans/spring-beans-3.0.xsd

                                                                                    http://www.springframework.org/schema/context

http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd

                               tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

                                                                   /spring-task-3.0.xsd"

default-lazy-init="false">

Note: Theoretically Just add the configuration sentence . These parameters are not required.

Ok configuration is complete. Of course, the spring task still has many parameters. I will not explain them one by one. For details, please refer to the xsd document http://www.springframework.org/schema/task/spring-task- 3.0.xsd.

Appendix:

cronExpression configuration instructions, specific usage and parameters please Baidu google

Fields Allowed values ​​Allowed special characters

Seconds 0-59 , - * /

points 0-59 , - * /

hour 0-23 , - * /

date 1-31 , - * ? / L W C

month 1-12 or JAN-DEC , - * /

Weekday 1-7 or SUN-SAT , - * ? / L C #

Year (optional) Leave blank, 1970-2099 , - * /

-Interval

* Wildcard

? You don’t want to set that field

Here are just a few examples

CRON expression Meaning

"0 0 12 * * ?" Triggered every day at 12 noon

"0 15 10 ? * *" Triggered every morning at 10:15

"0 15 10 * * ?" Triggered every morning at 10:15

"0 15 10 * * ? *" Triggered every morning at 10:15

"0 15 10 * * ? 2005" Triggered every morning at 10:15 in 2005

"0 * 14 * * ?" Triggered once every minute from 2pm to 2:59 every day

"0 0/5 14 * * ?" Every day from 2pm to 2: Triggered every 5 minutes at the end of 55 minutes

"0 0/5 14,18 * * ?" Every 5 minutes during the two time periods of 2 pm to 2:55 and 6 pm to 6:55 every day Trigger

"0 0-5 14 * * ?" Trigger every minute from 14:00 to 14:05 every day

"0 10,44 14 ? 3 WED" Every Wednesday at 14:10 in March And trigger at 14:44

"0 15 10? * MON-FRI" Trigger at 10:15 every Monday, Tuesday, Wednesday, Thursday, Friday




More For articles related to several methods of java timer, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn