Java 在while循环中更新Calendar.SECOND

Java 在while循环中更新Calendar.SECOND,java,static,while-loop,calendar,Java,Static,While Loop,Calendar,我的目标是用java运行一个程序,在每天的某个时间执行一系列代码 我知道TimerTask和Timer实用程序,但有理由不使用它们。 我的大部分代码在while循环下运行,条件是线程仍然处于活动状态 一些声明: static int theHour; static int theMinute; static int theSecond; 我的while循环的开始: while (this.threadAlive) { System.out.println("START thread");

我的目标是用java运行一个程序,在每天的某个时间执行一系列代码

我知道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
}

第二个的结果是正确的,但在再次循环后,它不会更新。我的声明是在类中全局定义的,我曾尝试将它们声明为
int
,但这并没有什么区别。我做错了什么?

答案是您的第二个变量被声明为静态。这意味着一旦设置了一次该值,就不能对其进行更改

去掉“静电”,你就可以走了


编辑:我现在看到您提到您尝试过不使用静态。我现在想知道,您是否运行了以前编译过的代码版本,但仍然将其视为静态的?我看不出这是一个问题的其他原因。

以下内容将解决您的问题:

尝试在循环开始时添加以下内容:

Calendar theTime = Calendar.getInstance();

谢谢

它正在运行,并且打印出来的速度比系统时钟更新的速度要快得多。如果while循环像print语句一样简单,这将是正确的。我提到的代码列表指的是连接到微控制器,获取数据,断开连接,睡眠,然后重新开始。我将发布更多代码,以提供更好的图片时间设置在哪里,以及如何在循环中更新?是的,感谢您注意到这一点。我看不出它将如何运行以前编译的版本。我在Eclipse中工作,在运行之前已经保存并编译了程序。您可以尝试执行以下操作:System.out.println(theTime.get(Calendar.SECOND));(而不是打印“theSecond”),在这种情况下,它是否仍然打印相同的值?
static
与“一旦设置一次值,它就无法更改”无关。这是一个有趣的建议,但是的,我尝试时它仍然打印相同的值。现在我们知道它不涉及变量。尝试在循环的开始处添加:Calendar theTime=Calendar.getInstance();
Calendar theTime = Calendar.getInstance();