java timed tasks Timer and TimerTask use detail

  • 2020-06-07 04:26:07
  • OfStack

timer and timertask are built-in timed task implementations of jdk and do not need to import third-party jar packages to complete

1. Specify how long it will take to execute this task. Note: it will only execute once


public class TimerTest {
 Timer timer;
 public TimerTest(int time){
  timer = new Timer();
  timer.schedule(new timerTaskTest(),time*1000);//timer.schedule( Method to execute and how long to delay execution (ms))
 }

 public static void main(String[] args) {
  System.out.println("timer begin...");
  new TimerTest(3);
 }

 class timerTaskTest extends TimerTask{
  @Override
  public void run() {
   System.out.println("time's up!!");
  }
 }
 }

2. Perform tasks at specified times


public class TimerTest1 {
  Timer timer;

  public TimerTest1(){
    Date time = getTime();
    System.out.println(" Specify a time time="+time);
    timer = new Timer();
    timer.schedule(new TimerTaskTest1(),time);//timer.schedule( Method of execution, time to execute )
  }

  public Date getTime(){// Set the execution time 
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR,5);
    calendar.set(Calendar.MINUTE,46);
    calendar.set(Calendar.SECOND,00);
    Date time = calendar.getTime();

    return time;
  }

  public static void main(String[] args) {
    new TimerTest1();
  }

  class TimerTaskTest1 extends TimerTask{
    public void run() {
      System.out.println(" Specify a time to execute the thread task ...");
    }
  }
}

3. After the specified delay, the timer task is performed in a specified interval


public class TimerTest2 {
  Timer timer;
  public TimerTest2(){
    timer = new Timer();
    timer.schedule(new TimerTaskTest2(),1000,2000);//tiemr.schedule( Method of execution , Delay time , How long does it take to perform 1 time )
  }

  class TimerTaskTest2 extends TimerTask{
    @Override
    public void run() {
      System.out.println(" The execution time of this task "+new Date());
    }
  }

  public static void main(String[] args) {
    new TimerTest2();
  }
}

At this point the timing task implementation class is complete, and if it is an web project, you need to configure the startup in web.xml


<listener> 
    <listener-class>com.sxl.ContextListener</listener-class>  
</listener>

Configuration is complete.


Related articles: