Assign a value to a variable for a limited time only

scala

Solution

The timestamp idea is pretty easy to implement (here the argument is in seconds):

class TransientlyTrue(duration: Double) {
  private[this] val createdAt = System.nanoTime
  def value = (System.nanoTime-createdAt)*1e-9 <= duration
}
implicit def TransientToBoolean(t: TransientlyTrue) = t.value

With the implicit conversion you can transparently drop this in wherever you need a `Boolean`. Or you could leave that off and just call `.value`.

Problem

Let's say that there is a boolean variable, initially assigned the value `false`. Is there a way to say, let this variable be `true` for the next 5 minutes and then let it be `false` again? My current idea is that I could store the variable along with a timestamp, then as soon as the variable is turned to `true`, the timestamp is set to the current time, then check the variable's value through a method that will return `true` if the current time and the initial timestamp form a duration of less than 5 minutes and then `false` if the duration is greater than 5 minutes. I'm thinking about an implicit conversion from `Boolean` to a `RichBoolean` that would handle this mechanism through an elegant method name or something. Is there a more elegant or Scala native way of doing this?

Original source

Related problems