Home Java javaTutorial JAVA TIMER simple usage learning

JAVA TIMER simple usage learning

Jan 11, 2017 pm 04:12 PM

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

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

For more articles related to the simple usage of JAVA TIMER, 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles