May 10, 2021 Java
In development work, we often need to perform some periodic operations, such as every 5 minutes to perform a program, such as regularly checking the number of connections in the database connection pool, regularly backing up data every night, etc. , in java, the most convenient and efficient way to implement is to use java.util.Timer tool class, and then by scheduling java.util.TimerTask tasks, but in this way, although you can use this method to run at a certain frequency, but not at a specified time. H ere's a look at several common ways to set up java timers and how to stop them.
1,
create a thread, and then let it run in the while loop, through the sleep method to achieve the effect of timed tasks;
2.
With Timer and TimerTask, there are the following benefits compared to the first method:
Control when starting and canceling tasks
The first time you perform a task, you can specify the delay time you want
3,
with
ScheduledExecutorService
is introduced from
java.util.concurrent
as a concurrent tool class, which is the ideal timed task implementation, compared to the previous two methods, it has the following benefits:
Compared to Timer's single thread, it performs its tasks through a thread pool
You can be flexible enough to set the first task delay time
Provides a good convention to set the time interval for execution
4,
spring-based
framework of timed tasks to achieve:
You
can
use Quartz,
a powerful scheduler that lets your program execute at a specified time or
at a certain frequency.
In terms of how job classes are inherited, there are two types:
Job classes need to be inherited from specific job class base classes, such as Quartz from org.springframework.scheduling.quartz JobBean; java.util.Timer needs to inherit from java.util.TimerTask.
A job class is a normal java class and does not need to be inherited from any base class.
Note: The second method is recommended for comparison, because the classes are ordinary and do not need to be treated differently in advance.
From the trigger timing of the task scheduling, here are two main triggers used for the job:
Triggered every specified time, the trigger in Quartz is: org.springframework.scheduling.quartz.SimpleTriggerBean
Triggered every specified time, the scheduler in Quartz is: org.springframework.scheduling.quartz.CronTriggerBean
Note: Not every task can use these two triggers, such as the java.util.TimerTask task.
Both Quartz and Spring task support both trigger conditions.
Description of usage:
First, the job 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;
public class Job1 extends QuartzJobBean {
private int timeout;
private static int i = 0;
//调度工厂实例化后,经过timeout时间开始执行调度
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* 要调度的具体任务
*/
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
System.out.println("定时任务执行中…");
}
}
Xml
code
<bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.gy.Job1" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="0" />
</map>
</property>
</bean>
Description:
org.springframework.scheduling.quartz.JobDetailBean
has two properties, the
jobClass
property, which is
the
task class we define
in java
code, and the
jobDataAsMap property,
which is the property value that needs to be
injected in that task class.
Step 3: Configure how job scheduling is triggered (triggers)
Quartz has two job triggers, one of which is
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
The first Simple TriggerBean only supports calling tasks at a certain frequency, such as every 30 minutes.
The configuration is as follows:
Xml
code
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="job1" />
<property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->
<property name="repeatInterval" value="2000" /><!-- 每2秒调度一次 -->
</bean>
The configuration is as follows:
Xml code
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="job1" />
<!—每天12:00运行一次 -->
<property name="cronExpression" value="0 0 12 * * ?" />
</bean>
See the
appendix for the syntax of
cronExpression
expressions.
Xml
code
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
Description: This parameter specifies the name of the trigger that was previously configured.
Step 5: Start your app and 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.MethodInvokingJobDetailFactoryBean
The two classes correspond to the two ways that spring supports task scheduling, namely, the timer task method and the Quartz method that java comes with. Here I only write about the use of MethodInvokingJobDetailFactoryBean, and the advantage of using this class is that our task class no longer needs to inherit from any class, but is a normal pojo.
Step 1: Write a task class
Java
code
public class Job2 {
public void doJob2() {
System.out.println("不继承QuartzJobBean方式-调度进行中...");
}
}
As you can see, this is a normal class, and there is 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>
Description: This step is a critical step, declaring a MethodInvoking JobDetailFactoryBean with two key attributes: targetObject specifies a task class, and targetMethod specifies the method to run. The next step is the same as the method, and the same is posted for completeness.
Step 3: Configure how job scheduling is triggered (triggers)
Quartz has two job triggers, one of which is
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
The first Simple TriggerBean only supports calling tasks at a certain frequency, such as every 30 minutes.
The configuration is as follows:
Xml code
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="job2" />
<property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->
<property name="repeatInterval" value="2000" /><!-- 每2秒调度一次 -->
</bean>
The second, Cron Trigger Bean, supports running once to a specified time, such as once a day at 12:00.
The configuration is as follows:
Xml
code
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="job2" />
<!—每天12:00运行一次 -->
<property name="cronExpression" value="0 0 12 * * ?" />
</bean>
The above two scheduling methods according to the actual situation, choose one can be.
Step 4: Configure the dispatch factory
Xml code
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
Description: This parameter specifies the name of the trigger that was previously configured.
Step 5: Start your app and deploy the project to tomcat or other containers.
At this end,
the basic configuration
of Quartz in
spring
is over, of course, before
using,
to import
the corresponding spring package and Quartz's
package, these are not out of
the question.
final Timer timer = new Timer();
TimerTask task = new TimerTask() {
private int count;
@Override
public void run() {
this.count++;
System.out.println(count);
if (count == 10) {
System.out.println("定时器停止了");
timer.cancel();// 停止定时器
}
}
};
timer.schedule(task, 0, 1000);// 1秒一次
Field
|
The allowed value
|
Special characters are allowed |
Seconds | 0-59 | , - * / |
points | 0-59 | , - * / |
Hours | 0-23 | , - * / |
Date | 1-31 | , - * ? / L W C |
Month | 1-12 or JAN-DEC | , - * / |
Week | 1-7 or SUN-SAT | , - * ? / L C # |
Year (optional) | Leave blank, 1970-2099 | , - * / |
- | Interval |
* | Wildcard |
? | You don't want to set that field |
CRON expression
|
Meaning |
"0 0 12 * * ?" | Triggered at twelve o'clock every day |
"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 in 2005 at 10:15 a.m |
"0 * 14 * * ?" | Triggers are triggered every minute from 2 p.m. to 2:59 p.m. daily |
"0 0/5 14 * * ?" | Triggers are triggered every 5 minutes from 2 p.m. to 2:55 p.m. daily |
"0 0/5 14,18 * * ?" | Triggers are triggered every 5 minutes every day from 2 p.m. to 2:55 p.m. and 6:55 p.m. to 6:55 p.m |
"0 0-5 14 * * ?" | Triggered every minute from 14:00 to 14:05 daily |
"0 10,44 14 ? 3 WED" | Triggered every Wednesday in March at 14:10 and 14:44 |
"0 15 10 ? * MON-FRI" | Triggered every Monday, Tuesday, Wednesday, Thursday, Friday at 10:15 |