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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks 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)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

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

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles