Search code examples
javatimerblocking

how to properly sleep in loop


I have a loop who's job is to act as a blocking command, execute a shell command once every second. Java warns about "sleeping in loop". Here is the code:

    while (!Shell.silentShellCommand(stringCommand).contains("Device detected")) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            log.errorHandler(ex);
        }
    }

Surely there is a better way to do this. I just don't know how. What would be the proper way to make a "blocking timer method"? I am using this to pause execution until the user does something.


Solution

  • Why not do something like this:

    public void loopMethod(){
        if(!Shell.silentShellCommand(stringCommand).contains("Device detected")){
            try {
                Thread.sleep(1000);
            } catch(InterruptedException ex) {
                ex.printStackTrace();
            }
            loopMethod();
        }
    }
    

    And just call that method from a background thread. Would that work? I mean, it's still technically a loop, but it looks cleaner for some reason!