public class JavaTimeTest { private final static Logger logger = Logger.getLogger("JavaTimeTest"); public JavaTimeTest() { } public static void main(String[] args) { class Test1 extends TimerTask { @Override public void run() { logger.info("begin running========="); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("end running========="); } } new Timer().scheduleAtFixedRate(new Test1(), 0, 1000); } } 測試結果: 十一月 15, 2016 9:40:11 下午 com.zzl.JavaTimeTest run 信息: begin running========= 十一月 15, 2016 9:40:14 下午 com.zzl.JavaTimeTest run 信息: end running========= 十一月 15, 2016 9:40:14 下午 com.zzl.JavaTimeTest run 信息: begin running========= 十一月 15, 2016 9:40:17 下午 com.zzl.JavaTimeTest run 信息: end running========= 十一月 15, 2016 9:40:17 下午 com.zzl.JavaTimeTest run 信息: begin running========= 十一月 15, 2016 9:40:20 下午 com.zzl.JavaTimeTest run 信息: end running========= 十一月 15, 2016 9:40:20 下午 com.zzl.JavaTimeTest run 信息: begin running=========
###ScheduledExecutorServiceide
public class ScheduleTimerTest { private final static Log log = LogFactory.getLog(ScheduleTimerTest.class); public ScheduleTimerTest() { } public static void main(String[] args) { class Test1 extends TimerTask { @Override public void run() { log.info("begin running========="); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("end running========="); } } //注意:直接將Test1做爲scheduleWithFixedDelay的參數,定時任務仍是會要在上次任務運行完以後才執行下次任務 //所以,如今定時任務只是每分鐘建立一個任務,真正的任務執行是在新建的線程中再執行 ScheduledExecutorService executor = Executors .newScheduledThreadPool(10); executor.scheduleWithFixedDelay( new Test1(), 0, //delay 1, //頻率 TimeUnit.SECONDS); } } 測試結果: 十一月 15, 2016 9:50:28 下午 com.zzl.ScheduleTimerTest run 信息: begin running========= 十一月 15, 2016 9:50:31 下午 com.zzl.ScheduleTimerTest run 信息: end running========= 十一月 15, 2016 9:50:32 下午 com.zzl.ScheduleTimerTest run 信息: begin running========= 十一月 15, 2016 9:50:35 下午 com.zzl.ScheduleTimerTest run 信息: end running========= 十一月 15, 2016 9:50:36 下午 com.zzl.ScheduleTimerTest run 信息: begin running========= 十一月 15, 2016 9:50:39 下午 com.zzl.ScheduleTimerTest run 信息: end running========= 十一月 15, 2016 9:50:40 下午 com.zzl.ScheduleTimerTest run 信息: begin running=========