定时处理任务Timer)
Timer类,是一种工具,可安排任务执行一次或者定期重复重复执行
public class OneTime { public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new MyTimerTask(); Date date = new Date(System.currentTimeMillis() + 3000); //过三秒之后执行任务 timer.schedule(task, date); } } public class MyTimerTask extends TimerTask{ @Override public void run() { System.out.println("MyTimerTask"); } }
public class RepeatDo { public static void main(String[] args) { Timer timer=new Timer(); //创建一个计时器过两秒后每隔3S 执行一次操作 timer.schedule(new MyTimerTask1(1,timer), 2000, 1L*3000); } } public class MyTimerTask1 extends TimerTask{ int round_id; Timer timer; public MyTimerTask1(int round,Timer timer) { this.round_id = round; this.timer = timer; } @Override public void run() { this.round_id++; System.out.println("repeat : " + this.round_id); //如果重复了4次之后就取消定时器 if(this.round_id == 5){ timer.cancel(); } } }
回忆过去,珍惜现在,放眼未来