Home Java javaTutorial Timer and TimerTask Examples of using timers and scheduled tasks in Java

Timer and TimerTask Examples of using timers and scheduled tasks in Java

Dec 16, 2016 pm 01:06 PM
java timer

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("________");     
        }     
    }    
}
Copy after login

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;     
        }     
    }     
      
}
Copy after login

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 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
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 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 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 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 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 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 use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles