import java.util.*;
public class TimerTaskDemo extends TimerTask{
public static void main(String args[])
{
//创建一个计时器任务调度和一个计时器来实现所需的结果
TimerTask timeTaskDemo = new TimerTaskDemo();
//初始化一个Timer
Timer timer = new Timer();
System.out.println("Task started: " + new Date());
//调度上面创建的timer
//将指定的任务安排在指定的延迟之后,重复固定的固定时间执行。随后的执行将按一定的时间间隔进行,由指定的时间间隔分隔。
//Signature of scheduleAtFixedRate(TimerTask task, long delay, long period)
timer.scheduleAtFixedRate(timeTaskDemo, 1, 1000);
try{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
//这里进行异常的处理
}
//调用timer
timer.cancel();
System.out.println("Task stopped: " + new Date());
}
// 该方法执行具体任务
public void run() {
System.out.println("In run method. Tasks that need to be executed can he invoked here");
}
}
https://blog.xqlee.com/article/216.html