import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; class MyTimerTask extends TimerTask{ SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void run() { // TODO Auto-generated method stub System.out.println(dateFormat.format(new Date())); } } public class Test { public static void main(String args[]){ MyTimerTask myTimerTask=new MyTimerTask(); Timer timer=new Timer(); timer.schedule(myTimerTask,1000,1000); System.out.println("Main end."); } }
运行结果:
Main end. 2013-12-04 14:18:57 2013-12-04 14:18:58 2013-12-04 14:18:59 2013-12-04 14:19:00 2013-12-04 14:19:01 2013-12-04 14:19:02 2013-12-04 14:19:03