search
HomeJavajavaTutorialUsage of JDK Timer timer

Usage of JDK Timer timer

Jun 28, 2017 am 10:34 AM
jdktimer

Implementing and scheduling a task to be executed by a timer
1) Implement a custom subclass of TimerTask. The run method contains the code that performs the task.
    class RemindTask extends TimerTask {
        public void run() {
            System.out.println("Time up!");
            System.exit(0);
        }
    }
2) Create a thread by instantiating the Timer class
    Timer timer = new timer();
3) Instantiate the timer task object(new RemindTask())
    RemindTask task = new RemindTask();
4) Schedule the timer task for execution.
  (1) execute the task after special milliseconds delay.
    timer.schedule(task,5*1000);
  (2) specify the time when the task suould execute.
    //execute the task at 11:01 p.m
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,23);
    calendar.set(Calendar.MINUTE,1);
    calendar.set(Calendar.SECOND,0);
    Date time = calendar.getTime();

    timer.schedule(task,time);

Stopping Timer Threads
  By defaulst, aprogram keeps running as long as its timer threads are running. There is four ways to terminate a timer thread
  1) Invoke cancel on the timer.(timer.cancel())
  2) Make the timer's thread a daemon(后台), by creating the timer like this: new Timer(true). If the only threads left in the program are daemon threads, the program exits.
  3) After all the timer scheduleds tasks have finished executing,remove all references to the Timer object. the timer thread will terminate.
  4) Invoke the System.exit method, which makes the entire program and all its threads exit.

Performing a Task repeatedly
There is four Timer method to perform a task repeatedly
  * schedule(TimerTask task, long delay, long period)
    Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
    执行重复的任务,第一次在延时时间后执行,往后的以特定的时间间隔执行
    timer.schedule(new RemindTask(),3*1000,1*1000)
    RemindTask任务将会在3秒后执行,以后将会以1秒的间隔重复执行

  * schedule(TimerTask task, Date time, long period)
    执行重复的任务,第一次在特定的时间执行,往后的以特定的时间间隔执行

  * scheduleAtFixedRate(TimerTask task, long delay, long period)
    Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
    以固定的延时执行重复的任务,首次执行在特定的延时之后,以后的执行发生在特定的时间间隔之后
    temer.scheduleAtFixedRate(new RemindTask(),3*1000,1*1000)
  * scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
    执行重复的任务,第一次在特定的时间执行,往后的以特定的时间间隔执行

  schedule和scheduleAtFixedRate的区别在于,schedule以固定的相对时间间隔执行,如果某一次执行被延时了,往后的执行的执行时间也会相对延时;而scheduleAtFixedRate是以绝对的时间间隔执行,如果某一次执行被延时,它的后一次执行的延时将会缩短。

The above is the detailed content of Usage of JDK Timer timer. For more information, please follow other related articles on 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 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.

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

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 Article

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment