timer应用demo

package home.room.form.no;
/**
 * add by xuhaobo 20110413
 */
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


public class TimeTask {
	int times = 0;
	public static void main(String[] args) { 
        TimeTask tTask=new TimeTask();
        tTask.times =4;
        tTask.loopTimeVoid(1000);
    }
    //执行定时任务
    public void timeVoid(int time){
    	System.out.println("计时开始!");
        final Timer timer = new Timer();
        TimerTask tt=new TimerTask() { 
            @Override
            public void run() {
                System.out.println("到点啦!");
                timer.cancel();
            }
        };
        timer.schedule(tt, time);
    }
    //指定时间执行
    public void theTimeVoid(){
    	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();
        final Timer timer = new Timer();
        TimerTask tt=new TimerTask() { 
            @Override
            public void run() {
                System.out.println("到点啦!");
                timer.cancel();
            }
        };
        timer.schedule(tt, time);
    }
    //按间隔循环执行
    public void loopTimeVoid(int time){
    	System.out.println("计时开始!");
        final Timer timer = new Timer();
        TimerTask tt=new TimerTask() { 
        	int size =times;
            @Override
            public void run() {
                if(size >0){
                	System.out.println("---"+size);
                	size--;
                }else{
                	System.out.println("---结束");
                	timer.cancel();
                }
            }
        };
        timer.schedule(tt,0,time);
    }
}

你可能感兴趣的:(java,timer,定时任务,定时)