search
HomeJavajavaTutorialExamples of timers and scheduled tasks in Java

Examples of timers and scheduled tasks in Java

May 16, 2017 am 09:55 AM
timertaskscheduled tasks

This article mainly introduces examples of Timer and TimerTask timers and scheduled tasks in Java. It is of great practical value. Friends in need can refer to it.

These two classes are very convenient to use and can Complete most of our needs for timers

The Timer class is a class used to execute tasks. It accepts a TimerTask as a parameter

Timer has two modes for executing tasks, the most commonly used It 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("");   
    }   
  }  
}

This type of runtime:

Print "————" on the console 1 second after the program starts
After an interval of two seconds Then execute the run() method of MyTask and print "————"
This keeps looping
When the s character is entered on the console, the timer cancels the work
Jumps out of the entire loop
The program runs Finish!

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

This class creates two scheduled tasks, mytask1 and mytask2.

The mytask1 task is used in the same way 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 timer.

scheduleAtFixedRate() method is defined as follows in API1.6.0:

Schedule the specified task to start repeating at the specified time Executed at a fixed rate. Subsequent executions occur at approximately fixed intervals, separated by the specified period.

Approximately fixed time intervals mean 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.

【Related Recommendations】

1.

Special Recommendation: "php Programmer Toolbox" V0.1 version download

2.

Java Free Video Tutorial

3.

JAVA Tutorial Manual

The above is the detailed content of Examples of timers and scheduled tasks in Java. 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 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 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...

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

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

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 set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment