timer定时器

.概览

Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。

简单的一个例程:

import java.util.Timer;
import java.util.TimerTask;

/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/

public class Reminder {
Timer timer;

public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);

}

class RemindTask extends TimerTask {
public void run() {

System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}

public static void main(String args[]) {
System.out.println("About to schedule task.");
new Reminder(5);
System.out.println("Task scheduled.");
}
}


运行这个小例子,你会首先看到:

About to schedule task.

5秒钟之后你会看到:

Time's up!

这个小例子可以说明一些用Timer线程实现和计划执行一个任务的基础步骤:

  • 实现自定义的TimerTask的子类,run方法包含要执行的任务代码,在这个例子里,这个子类就是RemindTask。
  • 实例化Timer类,创建计时器后台线程。
  • 实例化任务对象 (new RemindTask()).
  • 制定执行计划。这里用schedule方法,第一个参数是TimerTask对象,第二个参数表示开始执行前的延时时间(单位是milliseconds,这里定义了5000)。还有一种方法可以指定任务的执行时间,如下例,指定任务在11:01 p.m.执行:
//Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();

timer = new Timer();
timer.schedule(new RemindTask(), time);
原文地址:https://www.cnblogs.com/qqzy168/p/3136165.html