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

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











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
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
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.