search
HomeJavajavaTutorialJAVA TIMER simple usage learning

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. Look at a simple example:

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 ch = System.in.read();
                if(ch-'c'==0){ 
                    timer.cancel();//使用这个方法退出任务

                }
            } catch (IOException e) { 
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } 
    }

    
    static class MyTask extends java.util.TimerTask{ 
        @Override
        public void run() { 
            // TODO Auto-generated method stub
            System.out.println("________");
        }
    }
    }

If you are using JDK 5+, there is also a scheduleAtFixedRate mode available. In this mode, the Timer will Try to run the task at a fixed frequency. For example: In the above example, we want MyTask to be executed every two seconds after 1 second, but because java is not real-time (in fact, java is very real-time) Poor...), so the original meaning we expressed in the previous program cannot be strictly enforced. If we call scheduleAtFixedRate, then Timer will try to keep the execution frequency of your Task at every 2 seconds. . Run the above program, assuming that scheduleAtFixedRate is used, then the following scenario is possible: After 1 second, MyTask is executed once. Because the system is busy, MyTask is executed a second time after 2.5 seconds, and then the Timer records After setting this delay and trying to make up for this delay in the next task, then, after 1.5 seconds, MyTask will be executed three times. "Execute a task at a fixed frequency instead of a fixed delay time"

A more complicated example is given below, which tells you how to exit a single TimerTask and how to exit all Tasks

package MyTimerTest;
import java.io.IOException;
import java.util.Timer;
/* 
 * 本类给出了使用Timer和TimerTaske的主要方法,其中包括定制任务,添加任务
 * 退出任务,退出定时器.
 * 因为TimerTask的status域是包级可访问的,所以没有办法在java.util.包外
 * 得到其状态,这对编程造成一些不便 .我们不能判断某个Task的状态了.
 * 
 */
public class TimerTest {
    public static void main(String[] args) { 
        Timer timer = new Timer();
        MyTask myTask1 = new MyTask();
        MyTask myTask2 = new MyTask(); 
        myTask2.setInfo("myTask-2");
        timer.schedule(myTask1, 1000, 2000);
        timer.scheduleAtFixedRate(myTask2, 2000, 3000); 
        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();//退出单个任务
                    // 其实应该在这里判断myTask2是否也退出了,是的话就应该break.但是因为无法在包外得到
                    // myTask2的状态,所以,这里不能做出是否退出循环的判断. 
                } else if (strInfo.startsWith("Cancel-2")) {
      myTask2.cancel();
                } 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 = "^_^";
        @Override
        public void run() {

            // TODO Auto-generated method stub
            System.out.println(info);
        }
  public String getInfo() { 
            return info;
        }
        public void setInfo(String info) {

            this.info = info;
        }
    }
}

For more articles related to the simple usage of JAVA TIMER, 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
How to convert names to numbers to implement sorting within groups?How to convert names to numbers to implement sorting within groups?Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

In Java remote debugging, how to correctly obtain constant values ​​on remote servers?In Java remote debugging, how to correctly obtain constant values ​​on remote servers?Apr 19, 2025 pm 01:54 PM

Questions and Answers about constant acquisition in Java Remote Debugging When using Java for remote debugging, many developers may encounter some difficult phenomena. It...

In back-end development, how to distinguish the responsibilities of the service layer and the dao layer?In back-end development, how to distinguish the responsibilities of the service layer and the dao layer?Apr 19, 2025 pm 01:51 PM

Discussing the hierarchical architecture in back-end development. In back-end development, hierarchical architecture is a common design pattern, usually including controller, service and dao three layers...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.