Matt Smith
Matt Smith

Reputation: 975

Making a boolean true for x seconds when condition is met, then reverting it to false

I'm making a boolean so if a certain condition is met, it will return true for 3 seconds, but after that it will return false again.

So it's like

private boolean timedBoolean() {

         if(//condition to set boolean true){ 
            return true;
         }

        //if condition isn't met for 3 seconds
         return false;
     }

Been thinking about this for an hour now. Researched SO before I asked.

Upvotes: 6

Views: 3169

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200168

Remember the moment at which your 3-second period started:

private volatile long start;

and have the method check the elapsed time:

private boolean timedBoolean() {
    if (conditionMet()) {
      start = System.nanoTime();
      return true;
    }
    return System.nanoTime()-start < TimeUnit.SECONDS.toNanos(3);
}

Upvotes: 5

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

Here'a a Timed class.

For a certain amount of time after you call it's tick method it will return one value from its get method - then it will revert to it's other value. You should be able to use it for your case.

class Timed<T> {
  private final T recent;
  private final T old;
  private final long wait;
  // Last time we ticked.
  private long time = 0;

  public Timed (T recent, T old, long wait ) {
    this.recent = recent;
    this.old = old;
    this.wait = wait;
  }

  public T get () {
    return System.currentTimeMillis() < time + wait ? recent: old;
  }
  public void tick () {
    time = System.currentTimeMillis();
  }
}

...
Timed<Boolean> timed = new Timed<>(Boolean.TRUE, Boolean.FALSE, 3 * 1000);

Upvotes: 2

Saeed
Saeed

Reputation: 7370

private long lastTrueTime;
private boolean timedBoolean() {
        long now= System.currentTimeMillis();
        if(/*condition to set boolean true*/){ 
            lastTrueTime=now;
            return true;
        }

        if (lastTrueTime+3000<now)
            return false;

        return true;
}

Upvotes: 2

Related Questions