Four ways to use timers in Java

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

For the development of the game project compatriots, Timer this thing is certainly not strange, today, I often used before the timing of a small summary! Did not write the specific implementation of the principle, just listed four of the more common use methods, relatively speaking, so as long as the examples listed by its imitation can!


import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimeTest {
  public static void main(String[] args) {
    timer1();
    //timer2();
    //timer3();
    //timer4();
  }

  //The first method: set the task to execute the schedule(TimerTask task, Date time) at the specified time.
  public static void timer1() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      public void run() {
        System.out.println("------- Sets the task to be specified --------");
      }
    }, 2000);//Sets the specified time time, 2000 milliseconds here
  }

  //The second method: set the specified task task to execute the fixed delay peroid after the specified delay
  // schedule(TimerTask task, long delay, long period)
  public static void timer2() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      public void run() {
        System.out.println("------- Sets the task to be specified --------");
      }
    }, 1000, 5000);
  }

  //Third method: set the specified task task to execute the fixed frequency peroid after the specified delay.
  // scheduleAtFixedRate(TimerTask task, long delay, long period)
  public static void timer3() {
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
        System.out.println("------- Sets the task to be specified --------");
      }
    }, 1000, 2000);
  }
  
  //Fourth method: schedule the specified task to execute a repeated fixed-rate period starting at the specified time firstTime.
  // Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period)
  public static void timer4() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 12); //When the control
    calendar.set(Calendar.MINUTE, 0);    //The control points
    calendar.set(Calendar.SECOND, 0);    //Control the seconds

    Date time = calendar.getTime();     //Figure out the time to execute the task, which is 12:00pm today

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
        System.out.println("------- Sets the task to be specified --------");
      }
    }, time, 1000 * 60 * 60 * 24);//Here is set to delay the fixed execution every day
  }
}


Related articles: