Java定时器
-
public Timer():构造一个定时器
-
成员方法
public void schedule(TimerTask task,Date time); public void schedule(TimerTask task,long millis); public void schedule(TimerTask task,Date time,long period); public void schedule(TimerTask task,long millis,long period);
-
案例演示
public class TestTimerDemo { public static void main(String[] args) { //1.创建定时器 Timer timer = new Timer(); //2.布置任务 //一次性定时器 timer.schedule(new TimerTask() { @Override public void run() { System.out.println("时间到了下课..."); } },5000); Calendar cc = Calendar.getInstance(); cc.add(Calendar.SECOND,5); Date time = cc.getTime(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("时间到了下课..."); } },time); //周期定时器 timer.schedule(new TimerTask() { @Override public void run() { System.out.println("时间到了下课..."); } },5000,2000); Calendar cc1 = Calendar.getInstance(); cc1.add(Calendar.SECOND,5); Date time1 = cc1.getTime(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("时间到了下课..."); } },time1,1000); } }