2014-10-08 47 views
0

我的目標是運行一個java程序,每天在特定時間執行一個代碼列表。在while循環中更新Calendar.SECOND

我知道TimerTask和Timer實用程序,但有一個原因,不使用這些。 我的很多代碼都是在while循環下運行的,條件是線程仍然活着。

一些聲明:

static int theHour; 
static int theMinute; 
static int theSecond; 

我while循環的開頭:

while (this.threadAlive) 
{ 
    System.out.println("START thread"); 
    theHour = theTime.get(Calendar.HOUR_OF_DAY); 
    theMinute = theTime.get(Calendar.MINUTE); 
    theSecond = theTime.get(Calendar.SECOND); 
    System.out.println("the second is: " + theSecond); 
    //... 
    //... 
    //... 
    try 
    { 
     if (theHour == 12 && theMinute == 39 && (theSecond >= 0 || theSecond < 10) ) 
     { 
     System.out.println("In the loop"); 
     if (super.connectToDevice()) 
     { 
      // Send the data command to the device 
      //out.println(COMMAND_GP); 
      System.out.println("Simulation of midnight is successful"); 

      // Read and store the data returned from the device 
      String data = in.readLine(); 

      data = "test gps data"; 
      // Send the data off to be processed 
      sendDataForProcessing(data); 

      // Disconnect from the device 
      super.disconnectFromDevice(); 


     } 

     } 

     //Catch any exceptions here 
} 

約10秒鐘運行後的結果在控制檯:

START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 
START thread 
the second is: 46 

結果我得到theSecond是正確的,但它再次通過循環後從未更新。我的聲明是在全球範圍內定義的,我已經試過聲明他們,只是int,但這沒有什麼區別。我做錯了什麼?

+0

它正在運行並打印出來比系統時鐘更新要快得多 – ControlAltDel 2014-10-08 20:20:53

+0

如果while循環與打印語句一樣簡單,那麼情況就是如此。我提到的代碼列表是指連接到微控制器,抓取數據,斷開連接,睡眠然後再次恢復 – KS7X 2014-10-08 20:25:29

+0

聽起來很複雜 – ControlAltDel 2014-10-08 20:28:17

回答

1

下面將解決你的問題:

試着在你循環的開始添加此:

Calendar theTime = Calendar.getInstance(); 

謝謝!

0

答案是您的theSecond變量聲明爲靜態。這意味着一旦您設置了一次值,它就不能被更改。

拿出「靜態」,你會很好去。

編輯:我現在看到你已經提到你已經嘗試過沒有靜態。我現在想知道你是否正在運行一個以前編譯的代碼版本,它仍然將它視爲靜態代碼?我沒有看到其他原因,這將是一個問題。

+0

是的,謝謝你注意到胡安。我看不到它會如何嘗試運行先前編譯的版本。我在Eclipse中工作並在運行之前保存並編譯了程序。 – KS7X 2014-10-08 20:28:24

+0

您可以嘗試下列操作:System.out.println(theTime.get(Calendar.SECOND)); (而不是打印「theSecond」),在這種情況下它是否仍然打印相同的值? – 2014-10-08 20:29:30

+0

'static'與「一次設置值無法更改」無關。 – 2014-10-08 20:36:30