Recently, I need to perform some scheduled tasks in the project development. For example, I need to analyze the log information of the previous day at dawn every day, so I took this opportunity to sort out several implementation methods of scheduled tasks. Since the project adopts the Spring framework, I will combine all of them
The Spring framework.
one classification
In terms of the classification of technologies implemented, there are currently three main technologies (or products) :
- Timer class. This class allows you to schedule a java.util.TimerTask. This allows your program to run at a certain frequency, but not at a specified time. Generally used less, this article will not do a detailed introduction.
- Using Quartz, a powerful scheduler that allows your program to execute at a given time or at a given frequency, is a bit more complicated to configure, as I’ll explain later.
- Task, which comes with Spring3.0, can be thought of as a lightweight Quartz and is much simpler to use than Quartz, which I’ll cover later.
In terms of the inheritance mode of job class, it can be divided into two types:
- Working class to inherit from a specific job class base class, such as Quartz needs to inherit from org. Springframework. Scheduling. Quartz. QuartzJobBean; The java.util.Timer needs to be inherited from java.util.TimerTask.
- Job classes are plain Java classes and do not need to inherit from any base class.
Note: I recommend using the second method, because all the classes in this way are common and do not need to be treated differently in advance.
In terms of trigger timing of task scheduling, triggers used for jobs are mainly classified as follows:
- Every time, triggering a corresponding trigger in the Quartz is: org. Springframework. Scheduling. Quartz. SimpleTriggerBean
- Each to a specified time, triggering a corresponding in the Quartz scheduler is: org. Springframework. Scheduling. Quartz. CronTriggerBean
Note: Not every task can use either trigger; for example, the java.util.timerTask can only use the first trigger. Both Quartz and Spring Task support both triggers.
two instructions
This section describes how to use each task scheduling tool, including Quartz and Spring Task.
Quartz
The first kind, homework to class inherits from a specific base class: org. Springframework. Scheduling. Quartz. QuartzJobBean.
Step 1: Define the job class
Java code
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
publicclass Job1 extends QuartzJobBean {
privateint timeout;
privatestaticint i = 0;
// After the scheduling factory is instantiated, scheduling starts after a timeout
publicvoid setTimeout(int timeout) {
this.timeout = timeout;
}
/** * The specific task to be scheduled */
@Override
protectedvoid executeInternal(JobExecutionContext context)
throws JobExecutionException {
System.out.println("Scheduled task in progress..."); }}Copy the code
Step 2: Configure the job class JobDetailBean in the Spring configuration file
Xml code
<bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.gy.Job1"/>
<property name="jobDataAsMap">
<map>
<entrykey="timeout" value="0"/>
</map>
</property>
</bean>
Copy the code
Description: org. Springframework. Scheduling. Quartz. JobDetailBean has two attributes, jobClass attributes that we defined in Java code task class, jobDataAsMap namely the task need to inject in the class of attribute values.
Step 3: Configure job scheduling triggers (triggers)
Quartz has two types of job triggers, namely
-
org.springframework.scheduling.quartz.SimpleTriggerBean
-
org.springframework.scheduling.quartz.CronTriggerBean
The first type of SimpleTriggerBean supports only invoking tasks at a certain frequency, such as every 30 minutes.
The configuration mode is as follows:
Xml code
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="job1"/>
<property name="startDelay" value="0"/>
<property name="repeatInterval" value="2000"/>
</bean>
Copy the code
The second type of CronTriggerBean supports running at a specified time, such as 12:00 a day.
The configuration mode is as follows:
Xml code
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="job1"/>
>
<property name="cronExpression" value="0, 0, 12 * *?/>
</bean>
Copy the code
See appendix for syntax of cronExpression expressions.
Step 4: Configure the scheduling factory
Xml code
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
Copy the code
Note: This parameter specifies the name of the previously configured trigger.
Step 5: Just start your application, deploy the project to Tomcat or another container.
Second, the job class does not inherit from a particular base class.
Spring supports this approach thanks to two classes:
-
org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean
-
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
These two classes correspond to the two task scheduling methods supported by Spring respectively, namely the timer Task method and Quartz method of Java mentioned above. Here I only write MethodInvokingJobDetailFactoryBean usage, the use of this class is that the benefits of our task class no longer need to inherit from any class, but ordinary pojos.
Step 1: Write the task class
Java code
publicclass Job2 {
publicvoid doJob2(a) {
System.out.println("Do not inherit QuartzJobBean mode - scheduling in progress..."); }}Copy the code
As you can see, this is just a normal class and it has a method.
Step 2: Configure the job class
Xml code
<bean id="job2"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<bean class="com.gy.Job2"/>
</property>
<property name="targetMethod" value="doJob2"/>
<property name="concurrent" value="false"/>
</bean>
Copy the code
Note: this step is the key step, declare a MethodInvokingJobDetailFactoryBean, there are two key attributes: targetObject class specified tasks, targetMethod specified operation methods. The next step is the same as method 1. For completeness, post the same.
Step 3: Configure job scheduling triggers (triggers)
Quartz has two types of job triggers, namely
- org.springframework.scheduling.quartz.SimpleTriggerBean
- org.springframework.scheduling.quartz.CronTriggerBean
The first type of SimpleTriggerBean supports only invoking tasks at a certain frequency, such as every 30 minutes.
The configuration mode is as follows:
Xml code
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="job2"/>
<property name="startDelay" value="0"/>
<property name="repeatInterval" value="2000"/>
</bean>
Copy the code
The second type of CronTriggerBean supports running at a specified time, such as 12:00 a day.
The configuration mode is as follows:
Xml code
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="job2"/>
>
<property name="cronExpression" value="0, 0, 12 * *?/>
</bean>
Copy the code
You can choose either of the above two scheduling modes based on the actual situation.
Step 4: Configure the scheduling factory
Xml code
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
Copy the code
Note: This parameter specifies the name of the previously configured trigger.
Step 5: Just start your application, deploy the project to Tomcat or another container.
This completes the basic configuration of Quartz in Spring, of course, before using it, import the corresponding Spring package and Quartz package, which need not be said more.
In fact, Quartz configuration looks quite complicated, because Quartz is actually a heavyweight tool, if we just want to perform a few simple timed tasks, is there a simpler tool? Yes!
See my introduction to Spring Task below.
Spring-Task
In the previous section, we introduced Spring Task, a new scheduled task tool developed after Spring3.0, which can be compared to a lightweight Quartz and is easy to use, requiring no additional packages other than spring-related packages. Annotations and configuration files are also supported
The following two methods will be introduced respectively.
The first method is configuration file
Step 1: Write the job class
Plain POJO, as follows:
Java code
import org.springframework.stereotype.Service;
@Service
publicclass TaskJob {
publicvoid job1(a) {system.out. println(" Task in progress... ") ); }}Copy the code
Step 2: Add the namespace and description to the Spring configuration file header
Xml code
<beans xmlns="http://www.springframework.org/schema/beans"
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">
Copy the code
#### Step 3: Set specific tasks in the Spring configuration file
Xml code
<task:scheduled-tasks>
<task:scheduledref="taskJob"method="job1"cron="0 * * * * ?"/>
</task:scheduled-tasks>
<context:component-scanbase-package=" com.gy.mytask"/ >
Copy the code
Note: Ref parameter specifies the task class, method specifies the method to be run, cron and cronExpression, the specific writing method is not introduced here, see the appendix of the previous article for details. This configuration goes without saying. Spring scans annotations. At this point the configuration is complete, isn’t it very simple.
Second: use notes
Maybe we don’t want to have to configure each task class in an XML file. Instead, we can use the @scheduled annotation. 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
{
publicabstract String cron(a);
publicabstractlong fixedDelay(a);
publicabstractlong fixedRate(a);
}
Copy the code
You can see that the annotation has three methods, or parameters, that say:
- Cron: Specifies the CRON expression
- FixedDelay: 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. It is the interval from the completion of the previous task to the start of the next task, in milliseconds.
- FixedRate: 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. The interval from the start of the previous task to the start of the next task, in milliseconds.
So let me configure it.
Step 1: Write a POJO
Java code
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component(" taskJob ") publicclass taskJob {@Scheduled(cron = "0, 0, 3 * *?)
publicvoid job1(a) {system.out. println(" Task in progress... ") ); }}Copy the code
#### Step 2: Add task-related configuration:
Xml code
<?xml version="1.0" encoding="UTF-8"? >
<beans xmlns="http://www.springframework.org/schema/beans"
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"
xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
default-lazy-init="false">
<context:annotation-config/>
<context:component-scanbase-package="com.gy.mytask"/>
<task:annotation-drivenscheduler="qbScheduler" mode="proxy"/>
<task:schedulerid="qbScheduler" pool-size="10"/>
Copy the code
Note: In theory, you only need to add this configuration, these parameters are not necessary.
Ok configured, of course, the spring task still has a lot of parameters, I will not explain one by one, the specific reference XSD documents at http://www.springframework.org/schema/task/spring-task-3.0.xsd.
Appendix:
For the configuration description of cronExpression, please visit Baidu and Google for specific usage and parameters
Field allowed values allow special characters seconds 0-59, – * / minute 0-59, – * / hour 0-23, – * / date 1-31, – *? / L W C Month 1-12 or Jan-dec, – * / Week 1-7 or Sun-sat, – *? / L C # year (optional) left blank, 1970-2099, – * / – interval * wildcard? You don’t want to set that field and here’s just a few examples of CRON expressions that mean “0, 0, 12 * *?” “0, 15, 10? * * triggers “0 15 10 * *?” every morning at 10:15 am. “0, 15, 10 * *? *” Triggered every morning at 10:15 “0 15 10 * *? 2005 – “0 * 14 * *?” triggered at 10:15 am every day in 2005 Trigger “0/5 14 * *?” every minute from 2:00 p.m. to 2:59 p.m. every day. Trigger “0/5 14,18 * *?” every 5 minutes from 2:00 p.m. to 2:55 p.m. every day. “0 0-5 14 * *?” will be triggered every 5 minutes between 2 p.m. and 2:55 p.m. and 6 p.m. and 6:55 p.m. Trigger “0, 10,44, 14? 3 WED” Every Wednesday in March at 14:10 and 14:44 trigger “0 15 10? * Mon-fri “triggers every Monday, Tuesday, Wednesday, Thursday, and Friday at 10:15
Reprinted from: Simple Book – fold up low
Article: www.jianshu.com/p/ce38c5b6f…