竹十一
          在匆忙與奔走中墮落
          關(guān)于Timer運(yùn)行時(shí)修改系統(tǒng)時(shí)間

          對Sun JDK的Timer來說,系統(tǒng)時(shí)間修改到當(dāng)前時(shí)間之后,不會影響Timer的執(zhí)行;但是如果系統(tǒng)時(shí)間修改到當(dāng)前時(shí)間之前,就會導(dǎo)致Timer掛起。

          下面這段代碼就是根本原因了(取自sun jdk1.4.2 source code, java.util.Timer#mainLoop() line 415~426):

              currentTime 
          = System.currentTimeMillis();
              executionTime 
          = task.nextExecutionTime;
              
          if (taskFired = (executionTime<=currentTime)) {
                  
          if (task.period == 0) { // Non-repeating, remove
                      queue.removeMin();
                      task.state 
          = TimerTask.EXECUTED;
                  } 
          else { // Repeating task, reschedule
                      queue.rescheduleMin(
                        task.period
          <0 ? currentTime   - task.period
                                      : executionTime 
          + task.period);
                  }
              }

              注:period就是TimeTask初始化時(shí)設(shè)定的執(zhí)行間隔,taskFired是個(gè)boolean。
             
          從這段代碼可以看出,TimerTask執(zhí)行的條件是(executionTime<=currentTime)。其中executionTime取自TimerTask,而currentTime來自系統(tǒng)時(shí)間。原因就在于此,currentTime因?yàn)樾薷南到y(tǒng)時(shí)間而提前了,所以這個(gè)條件(executionTime<=currentTime)永遠(yuǎn)也不會達(dá)到,TimerTask將不會被執(zhí)行。

          避免方法:在修改系統(tǒng)時(shí)間后重新啟動應(yīng)用:)


          posted on 2007-12-04 16:40 竹十一 閱讀(4990) 評論(2)  編輯  收藏 所屬分類: JSE
          Comments
          • # re: 關(guān)于Timer運(yùn)行時(shí)修改系統(tǒng)時(shí)間
            北京時(shí)間
            Posted @ 2008-12-30 13:02
            TimerTask將不會被執(zhí)行。  回復(fù)  更多評論   
          • # re: 關(guān)于Timer運(yùn)行時(shí)修改系統(tǒng)時(shí)間[未登錄]
            aa
            Posted @ 2009-07-27 15:14
            好象不是,timer停止一段時(shí)間后又重新開始.我使用jdk1.6測試的,但是代碼和 jdk1.4.2 source code中的一樣.  回復(fù)  更多評論   

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
          博客園   IT新聞   Chat2DB   C++博客   博問  
           
           
          主站蜘蛛池模板: 贡山| 铜川市| 普安县| 镇江市| 洛南县| 永安市| 汝阳县| 惠水县| 方山县| 茂名市| 志丹县| 三穗县| 神农架林区| 重庆市| 奇台县| 大渡口区| 济阳县| 阜城县| 寻乌县| 额敏县| 上蔡县| 永胜县| 永清县| 大方县| 红桥区| 金山区| 上高县| 巴东县| 彭山县| 贵港市| 聂拉木县| 合作市| 林西县| 西盟| 英吉沙县| 龙陵县| 鄱阳县| 集贤县| 彩票| 西藏| 墨竹工卡县|