我的目标是运行一个 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/