KS7X
KS7X

Reputation: 342

Updating Calendar.SECOND in while loop

My objective is to run a program in java that performs a list of code at a certain time each day.

I am aware of the TimerTask and Timer utilities but there is a reason to not using those. Much of my code is run under a while loop with the condition that the thread is still alive.

Some declarations:

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

The beginning of my while loop:

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
}

The result in the console after about 10 seconds of runtime:

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

The result I get for theSecond is correct but it never updates after going through the loop again. My declarations are defined globally in the class and I have tried declaring them just as int but that did not make a difference. What is it that I am doing wrong?

Upvotes: 1

Views: 93

Answers (2)

Juan Martinez
Juan Martinez

Reputation: 111

The following will solve your problem:

Try adding this at the start of your loop:

Calendar theTime = Calendar.getInstance();

Thanks!!

Upvotes: 1

Juan Martinez
Juan Martinez

Reputation: 111

The answer is that your theSecond variable is declared as static. This means that once you set the value once, it cannot be changed.

Take out the "static" and you'll be good to go.

EDIT: I now see you've mentioned that you've tried w/o the static. I'm now wondering if somehow you're running a previously-compiled version of the code that is still treating it as static? I see no other reason this would be an issue.

Upvotes: 0

Related Questions