Home Java javaTutorial Implementation of timer, introduction to java timer Timer and Quartz and configuration of timer in Spring

Implementation of timer, introduction to java timer Timer and Quartz and configuration of timer in Spring

Dec 16, 2016 pm 01:23 PM
java timer

1 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


org.lzstone.action.LzstoneMain
gt;

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


org.lzstone.action.LzstoneMainListener


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)





< ;bean id="lzstoneTimeTask" class="org.lzstone.action.LzstoneTimeTask"/>




3000



4000









;

1.3 Startup settings in web projects
                                                                                                                       xml
                                                                                                                                                                                                       
                                                                                                                         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






< property name="targetObject">




execute










0 0 12 * * ?












2.3 Startup settings in web projects

contextConfigLocation
/WEB-INF/QuartzConfig.xml


;listener>

  

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!


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles