java - 在 while 循环中更新 Calendar.SECOND

标签 java static while-loop calendar

我的目标是运行一个 Java 程序,该程序在每天的特定时间执行一系列代码。

我知道 TimerTask 和 Timer 实用程序,但有理由不使用它们。 我的大部分代码都是在 while 循环下运行的,条件是线程仍处于 Activity 状态。

一些声明:

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 ,但这没有什么区别。我到底做错了什么?

最佳答案

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

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

Calendar theTime = Calendar.getInstance();

谢谢!!

关于java - 在 while 循环中更新 Calendar.SECOND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26265637/

相关文章:

java - PreparedStatement IF EXISTS 抛出 : org. postgresql.util.PSQLException : The column index is out of range: 1, 列数:0

java - 将静态变量值传递给另一个类

mysql - PHP PDO foreach 还是 while in slider?

mysql - 排除下拉列表中的状态

Java 8 并行流缩减——线程数与加速比

java - Android 上的协议(protocol)生成的 Grpc 服务中的方法编码器错误

java - 如果不修改静态类变量,非同步静态方法是否线程安全?

java - 在 Java 中,在一个子类中将变量设置为 Final 和 static,同时在其他子类中保持变量不变

python - 使用 while 循环从输入创建列表

java - 客户端无法从服务器接收信息