2014-10-08 46 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