search
HomeJavajavaTutorialTimer and TimerTask Examples of using timers and scheduled tasks in Java

These two classes are very convenient to use and can fulfill most of our needs for timers.
The Timer class is a class used to perform tasks. It accepts a TimerTask as a parameter.

Timer has two modes for executing tasks. The most commonly used is schedule, which can execute tasks in two ways: 1: at a certain time (Data), 2: after a fixed time (int delay). Both methods can specify the frequency of task execution.

TimerTest.Java

package com.cn;  
import java.io.IOException;  
import java.util.Timer;  
    
public class TimerTest{     
           
    public static void main(String[] args){     
        Timer timer = new Timer();     
        timer.schedule(new MyTask(), 1000, 2000);//在1秒后执行此任务,每次间隔2秒执行一次,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.     
        while(true){//这个是用来停止此任务的,否则就一直循环执行此任务     
            try{     
                int in = System.in.read();    
                if(in == 's'){     
                    timer.cancel();//使用这个方法退出任务     
                    break;  
                }     
            } catch (IOException e){     
                // TODO Auto-generated catch block     
                e.printStackTrace();     
            }     
        }     
    }    
      
    static class MyTask extends java.util.TimerTask{      
        public void run(){     
            System.out.println("________");     
        }     
    }    
}

This type of runtime:

Print "————" on the console 1 second after the program starts

After an interval of two seconds, the run() method of MyTask is executed and "————" is printed. —”

This keeps looping

When the s character is entered on the console, the timer cancels its work

jumps out of the entire loop

The program ends!


TimerTest2.java:

package com.cn;  
  
import java.io.IOException;  
import java.util.Date;  
import java.util.Timer;  
  
public class TimerTest2{     
        
    public static void main(String[] args){     
        Timer timer = new Timer();     
        MyTask myTask1 = new MyTask();     
        MyTask myTask2 = new MyTask();     
        myTask2.setInfo("myTask-info-2");     
          
        timer.schedule(myTask1, 1000, 2000);  //任务1 一秒钟后执行,每两秒执行一次。   
        timer.scheduleAtFixedRate(myTask2, 2000, 3000);   //任务2 2秒后开始进行重复的固定速率执行(3秒钟重复一次)  
          
        while (true){     
            try{     
                //用来接收键盘输入的字符串  
                byte[] info = new byte[1024];     
                int len = System.in.read(info);    
                  
                String strInfo = new String(info, 0, len, "GBK");//从控制台读出信息     
                  
                if (strInfo.charAt(strInfo.length() - 1) == ' '){     
                    strInfo = strInfo.substring(0, strInfo.length() - 2);     
                }    
                  
                if (strInfo.startsWith("Cancel-1")){     
                    myTask1.cancel();//退出任务1     
                    // 其实应该在这里判断myTask2是否也退出了,是的话就应该break.但是因为无法在包外得到     
                    // myTask2的状态,所以,这里不能做出是否退出循环的判断.     
                } else if (strInfo.startsWith("Cancel-2")){     
                    myTask2.cancel();  //退出任务2   
                } else if (strInfo.startsWith("Cancel-All")){     
                    timer.cancel();//退出Timer     
                    break;     
                } else{     
                    // 只对myTask1作出判断,偷个懒^_^     
                    myTask1.setInfo(strInfo);     
                }     
            } catch (IOException e){     
                // TODO Auto-generated catch block     
                e.printStackTrace();     
            }     
        }     
    }     
    
    static class MyTask extends java.util.TimerTask{     
          
        String info = "INFO";  
    
        @Override     
        public void run(){     
            // TODO Auto-generated method stub     
            System.out.println(new Date() + "      " + info);     
        }     
    
        public String getInfo(){     
            return info;     
        }     
        public void setInfo(String info){     
            this.info = info;     
        }     
    }     
      
}

This class creates two scheduled tasks mytask1 and mytask2


mytask1 task is used the same as the example in the TimerTest class above. That is, the specified task is scheduled to be executed with a fixed delay repeatedly starting from the specified delay.

The mytask2 task is different from the above usage. timer.scheduleAtFixedRate is executed using the scheduleAtFixedRate() method of the timer. The

scheduleAtFixedRate() method is defined in API 1.6.0 as follows:

Scheduling the specified task to start at the specified time for repeated fixed-rate execution. Subsequent executions occur at approximately fixed intervals (separated by the specified period).

Approximately fixed time intervals means that in fixed-rate execution, each execution is scheduled relative to the scheduled initial execution time. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in quick succession, allowing subsequent executions to catch up.



Other commonly used methods of the Timer class:

cancel()
Terminate this timer and discard all currently scheduled tasks.

purge()
Removes all canceled tasks from this timer's task queue.

schedule(TimerTask task, Date time)
Schedule the execution of the specified task at the specified time.


Other commonly used methods of the TimerTask class:

cancel()
Cancel this timer task.

run()
The operation to be performed by this timer task.

scheduledExecutionTime()
Returns the scheduled execution time of the most recent actual execution of this task.


For more examples of Timer and TimerTask usage in Java, 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
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version