简体   繁体   中英

How to check some condition every 1 sec in java until true

I need to check certain condition in java every 1 second until it is true.Once it is true, need to exit from it and proceed further.

Say a->b->c check b every 1 sec until it is true, if it is true go to c.

Could someone suggest what is the best possible way to achieve this in Java?

Here is what you need:

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!condition)
                    handler.postDelayed(this, 1000);
                else {
                    // do actions
                    condition = true;
                }
            }
        }, 1000);
    }

I think you should take a look at the Timer and TimerTask classes. You can use them to schedule certain tasks to take place after a certain amount of time.

You need to extend the 'TimerTask' class and override the run() method. For example, you could do something like this:

Here's an example, which prints Hello World every 5 seconds: -

class CheckCondition extends TimerTask {
    public void run() {
       // if some condition is true
          // do something 
    }
 }

Used from another method, which checks your condition once every second (the function takes milliseconds):

Timer timer = new Timer();

// timer.schedule(class, initial delay, interval in milliseconds)
timer.schedule(new CheckCondition(), 0, 1000);

One option is using the Handler 's postDelayed() method:

// do something A

do {
    // Execute some code after 1 second has passed
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
        public void run() { 
            // do something B
        } 
    }, 1000); 
}
while(condition);

// do something C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM