


Implementation of timer, introduction to java timer Timer and Quartz and configuration of timer in Spring
Dec 16, 2016 pm 01:23 PM1 The role of timer
In actual development, if the project needs to be executed regularly or a certain amount of work needs to be repeated, the timer is particularly important.
Of course, if we don’t understand the timer, we will use threads to implement it, for example:
package org.lzstone.action
public class FinanceAction extends Thread{
private Date date;
Thread.sleep((int)(Math.random()*1000));
date = new Date();
‐ ‐ through
}
}
}
Implementing the timer yourself is very complicated. If it is not implemented well and takes up too much memory, the system will be over. Therefore, timers are a good choice for handling scheduled or repeated tasks
2.java Common timers in
1) Implemented with Java.util.Timer
2) Implemented with Quartz provided by the OpenSymphony community
3. Introduction to Timer
Using Timer to develop scheduled tasks is mainly divided into two steps:
1) Create timing Task class 示 Example code:
package org.lzstone.ACTION
IMPORT JAVA.UTIL.TIMETASK
PUBLIC CLASS LZSTONETIMETASK EXTENDS TIMETASK {
Public Void Run () {
// Perseverance The timer task of the line 器}}
2) Run Scheduled tasks, there are two ways to run scheduled tasks:
2.1) The program starts directly
Sample code:
package org.lzstone.action
public class LzstoneMain{
…..
public void run(){
//Execute the timer task
// Create an instance
Timer timer = new Timer();
Parameters:
‐ ’ ’ s ‐ ‐ ‐‐‐‐‐‐‐‐ the task to be scheduled.
0- Delay time before executing the task, unit is milliseconds.
1*1000- The time interval between executing each subsequent task, in milliseconds.
timer.schedule(new LzstoneTimeTask(),0,1*1000);
}
}
2.2) Web monitoring method
Sample code:
package org.lzstone.action
public class LzstoneMain implements ServletContextListener{
private Timer timer = null;
use using using using using through using ’ ’s out of ’s ’ through using ‐ ‐ ‐nll;
}
public void contextDestroyed(ServletContextEvent event) { The last task performed by this timer.
timer.cancel();
web.xml configuration
<listener>
<listener-class>
org.lzstone.action.LzstoneMain
gt;
</listener>
4. Introducing Quartz
Quartz is another open source project in the field of job scheduling by the OpenSymphony open source organization. It can be used to create simple or complex scheduled tasks. The steps to develop scheduled tasks using Quartz are similar to the Timer class
.
Using Quartz to develop scheduled tasks is mainly divided into two steps:
1) Create a scheduled task class
Sample code:
package org.lzstone.action
public class LzstoneTimeTask implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException {行 // executing timer task
}}}}2) Run scheduled tasks. There are two ways to run scheduled tasks:
2.1) Start the program directly, create a task scheduler and configure the corresponding task plan
Sample code:
package org.lzstone.action
public class LzstoneMain{
private static Scheduler sched;
public static void run() throws Exception{
//Goal creation task plan
Crontrigger Trigger = New Crontrigger ("LZSTONETRIGGER", "LZSTONE", "0 0 12 * *?");
// 0 0 12 * *? Discard the daily at 12 o'clock at noon. StdSchedulerFactory().getScheduler();
sched.shutdown();
}
}
//Execute
public class Main{
…........
public void run(){
LzstoneMain.run(); ....
}
2.2) Web listening method
Sample code:
package org.lzstone.action
public class LzstoneMainListener implements ServletContextListener{
private Timer timer = null; public void contextInitialized(ServletContextEvent event){
. in.stop();
}
}
web. xml configuration
<listener>
<listener-class>
org.lzstone.action.LzstoneMainListener
</listener-class>
</listener>
5. Compare the
Timer method to implement the timer, the principle is simple, It is easy to implement. It is more convenient to perform simple tasks. The disadvantage is that the execution time cannot be determined and the dependence is relatively strong. The specified class must be inherited. The Quartz method is used to implement the timer. It is convenient and clearly specifies the startup time. The timing parameters are more flexible. It is easy to implement relatively complex scheduled tasks. The disadvantage is that you need to implement a specific interface and load its framework. Both methods have their own advantages and disadvantages. They can be used according to their characteristics in specific situations.
6. Spring scheduled tasks
Spring scheduled tasks provide support for both Timer and Quartz, and the implementation steps are basically the same
First configure Spring’s support for Timer
1.1 Create a scheduled task class
package org.lzstone.action
import java.util .TimeTask
public class LzstoneTimeTask extends TimeTask{
public void run() use using use using through using ’s through through using ’s way through through through out through through through off ’s ‐ ‐ ‐ ‐ ‐ to to. Create the TimerConfig.xml file (generally called applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN// EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean>
<!--Register scheduled execution task entity-->
< ;bean id="lzstoneTimeTask" class="org.lzstone.action.LzstoneTimeTask"/>
<!--Register timer information-->
<bean id="taskInfo" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<!--Required before executing the task for the first time The waiting time is set to 3 seconds here-->
<property name="delay">
<value>3000</value>
</property>
<!--Set the execution of the task The period is set to 4 seconds here-->
<property name="period">
<value>4000</value>
</property>
<!--Set the specific tasks to be executed here. Configure the timer for lzstoneTimeTask-->
<property name="timerTask">
<ref local="lzstoneTimeTask"/>
</property>
</bean>
<!-- Task scheduler-->
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<!--Registered timer list-->
<property name="scheduledTimerTasks"> ;
</beans>
1.3 Startup settings in web projects
xml</param-value>
listener>
Configure Spring’s support for Quartz
2.1 Create a scheduled task class
package org.lzstone.action
public class LzstoneQuartzTask{
public void execute(){
.2 Registration timing Task class, configure task plan and task scheduler
Create QuartzConfig.xml file (generally called applicationContext.xml) under the project's WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean> ;
<!--Register scheduled execution task entity-->
<bean id="lzstoneQuartzTask" class="org.lzstone.action.LzstoneQuartzTask"/>
<!--Register timer information- ->
<bean id="taskInfo" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!--Specify the scheduled task class to be executed Here is LzstoneQuartzTask-->
< property name="targetObject">
<ref local="lzstoneQuartzTask"/>
</property>
<!--Specify the method name to be executed by the timer task class. Here is execute-->
<property name="targetMethod">
<value>execute</value>
</property>
</bean>
<!--Configure the scheduler for timer tasks-->
<bean id="quartzTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<!--Declare the entity to be run-->
<property name="jobDetail">
<ref local="taskInfo"/>
</property>
<!--Set the running time-->
<property name="cronExpression">
<value>0 0 12 * * ?</value>
</property>
</bean>
<!--Register listener-->
<bean id="registerQuartz" class="org.springframework.scheduling. quartz.SchedulerFactoryBean">
<!--Register timer entity collection-->
<property name="triggers">
<list>
<ref local="quartzTrigger"/>
</list>
</property>
</bean>
</beans>
2.3 Startup settings in web projects
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/QuartzConfig.xml</param-value>
</context-param>
;listener>
<listener-class>
More timer implementations and java timing For articles related to the introduction of Timer and Quartz and the configuration of timers in Spring, please pay attention to the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte

How does Java's classloading mechanism work, including different classloaders and their delegation models?

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?

Node.js 20: Key Performance Boosts and New Features

Iceberg: The Future of Data Lake Tables

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed

How to Share Data Between Steps in Cucumber
