Ammarah Ammarah - 1 month ago 5x
Java Question

I want to store continuous changing value of time in variable and then compare it with other times to do some tasks. how to do it

I want to store continuous changing value of time (in milliseconds) in a variable and then compare it with other time values to do some tasks. How to do it?
Problem is that once my program is compiled, the value of milliseconds stored in variable is same in the whole program and it never changes. All if conditions are compared with same time and the time on which I I want to do some task, never comes. I want comparison of time values with changing time of clock. I shall be very thankful for help.

Here's the code I am using for getting time continuously(I stored it in constructor):

Thread clock = new Thread(){

public void run() {
Calendar cal = Calendar.getInstance();
millisAt_ONU = cal.getTimeInMillis();




and I use this code to compare it with times (this is future timing - on which my condition will be executed:

if(millisAt_ONU == receivedGATE_time8){
//receivedGATE_time8 is the time which will come

try {
} catch (IOException e) {
// TODO Auto-generated catch block


System.out.println("Sent REPORT for ONU-8!");



Simply schedule the tasks to occur at specified times. In this example, MySystem is some class that you write to maintain the state of your process. It has methods someAction1(), someAction2(), … that contain actions like those shown in the question. And t1, t2, … are the delays, relative to "now" when you want those actions to occur.

MySystem system = ... /* Set up whatever you need as a context. */
ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(system::someAction1, t1, TimeUnit.MILLIS);
worker.schedule(system::someAction2, t2, TimeUnit.MILLIS);

You probably won't get millisecond precision. If you require precise timing, you may need to look into a realtime system.