Home  >  Article  >  Java  >  JAVA TIMER simple usage learning

JAVA TIMER simple usage learning

高洛峰
高洛峰Original
2017-01-11 16:12:401296browse

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

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

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