JAVA TIMER simple usage learning

  • 2020-04-01 02:05:45
  • OfStack

Timer has two modes of executing tasks. The most common one is schedule, which can execute tasks in two ways :1: ata certain time (Data) and 2: after a certain fixed time (int delay).


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);//Execute the task after 1 second, 2 seconds ata time, ata fixed time if you pass a Data parameter.
        while(true){//This is used to stop the task, otherwise the task will continue to loop
            try { 
                int ch = System.in.read();
                if(ch-'c'==0){ 
                    timer.cancel();//Use this method to exit the task

                }
            } 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,Timer tries to run tasks at a fixed frequency. , so, in our last program, we can express the original meaning is not strictly enforced. If we call the scheduleAtFixedRate, so, the Timer will try to keep your Task execution frequency in 2 seconds at a time. Running the above procedure, assuming that use scheduleAtFixedRate, then the following scenario is possible: 1 seconds, MyTask execution time, because the system is busy, MyTask after 2.5 seconds Then the Timer records the delay and tries to make up for it on the next task. After 1.5 seconds, MyTask will execute three times.

Here is a more complex example of how to exit a single TimerTask, and how to exit all tasks


package MyTimerTest;
import java.io.IOException;
import java.util.Timer;

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");//Read the information from the console
                if (strInfo.charAt(strInfo.length() - 1) == ' ') { 
                    strInfo = strInfo.substring(0, strInfo.length() - 2);
                }
                if (strInfo.startsWith("Cancel-1")) {                     myTask1.cancel();//Exit a single task
                    //Actually, it should be here to determine whether myTask2 has also exited. If so, it should break. However, it cannot be obtained outside the package
                    //The state of myTask2, therefore, cannot be made here whether to exit the loop or not.
                } else if (strInfo.startsWith("Cancel-2")) {
      myTask2.cancel();
                } else if (strInfo.startsWith("Cancel-All")) {
                     timer.cancel();//Out of the Timer
                    break;
                } else { 
                    //Only make judgment on myTask1, steal lazy ^_^
                    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;
        }
    }
}


Related articles: