線程--定時器

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("豬豬,該起牀了...");
	}
	
}
相關文章
相關標籤/搜索