Timer类:java
构造函数:timer(); 建立一个新的计时器
ide
方法:
函数
schedule
(
TimerTask task, Date time)
安排在指定的时间执行指定的任务this
schedule(TimerTask task, long delay, long period)
安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。spa
定时器使用示例:设计
public class TraditionalTimerTest { private static int count = 0; public static void main(String[] args) { /* new Timer().schedule(new TimerTask() { @Override public void run() { System.out.println("bombing!"); } }, 10000,3000);*/ class MyTimerTask extends TimerTask{ @Override public void run() { count = (count+1)%2; System.out.println("bombing!"); new Timer().schedule(/*new TimerTask() { @Override public void run() { System.out.println("bombing!"); } }*/new MyTimerTask(),2000+2000*count); } } new Timer().schedule(new MyTimerTask(), 2000); while(true){ System.out.println(new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
用此类设计一个定时在在某个时刻执行特定任务的类:code
public class TimerManager { private static final long PERIOD_TIME=24*60*60*1000; public TimerManager(){ //利用Calendar获取执行任务的时刻 Calendar calendar=Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 20); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); //得到第一次执行任务的时间 Date date=calendar.getTime(); if(date.before(new Date())) date=this.add(date, 1);//若这个时间已通过了,则将时间添加一天 Timer timer=new Timer(); Task task=new Task(); timer.schedule(task, date, PERIOD_TIME); } public Date add(Date date,int sum){ Calendar calendarST=Calendar.getInstance(); calendarST.setTime(date); calendarST.add(Calendar.DAY_OF_MONTH, sum); return calendarST.getTime(); } public static void main(String[] args) { new TimerManager(); } } class Task extends TimerTask{ @Override public void run() { // TODO Auto-generated method stub System.out.println("猪猪,该起床了..."); } }