Home  >  Article  >  Java  >  Examples of timers and scheduled tasks in Java

Examples of timers and scheduled tasks in Java

Y2J
Y2JOriginal
2017-05-16 09:55:591834browse

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