某些时候我们需要定时去完成一些任务,这里举一个例子:我们需要在3秒钟后打印当前系统时间,此后每隔5秒重复此操作。代码如下:
import java.util.TimerTask; import java.util.Date; import java.util.Timer; import java.text.SimpleDateFormat; class ShowDateTask extends TimerTask { public void run() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss:SSS"); System.out.println("当前时间是:" + sdf.format(new Date())); } } class Hello { public static void main(String[] args) { ShowDateTask sdt = new ShowDateTask(); Timer t = new Timer(); t.schedule(sdt,3000,5000); } public static void sleep(int timeSpan) { try { Thread.sleep(timeSpan); } catch (Exception e) { System.out.println(e); } } }