user1145280
user1145280

Reputation: 381

how to execute task within specified time in java

I have some function as

func1()
{
  while (true) 
  {
    isdateok()
    { // return true or false 
    }
  }
}

I want isdateok() should execute till 5 secs (or any timeout which is configured) if it returns true before the timeout then ok else continue and after 5 secs(or timeout) it should stop processing and return as timeout.

Upvotes: 1

Views: 178

Answers (2)

Pino
Pino

Reputation: 9303

I'm not sure I have understood your question, however the answer should be the following:

public boolean func1(long duration) {
    long t = System.currentTimeMillis();
    while (System.currentTimeMillis() - t < duration) {
        if (isdateok())
            return true;
        else
            Thread.yield();
    }
    return false;
}

Upvotes: 0

Alex Stybaev
Alex Stybaev

Reputation: 4693

Have a look at ScheduledExecutorService which will allow you to execute your time-dependent tasks.

Upvotes: 1

Related Questions