Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Last active November 23, 2015 13:17
Show Gist options
  • Select an option

  • Save MishaelRosenthal/c59d77492cd45bc8a99f to your computer and use it in GitHub Desktop.

Select an option

Save MishaelRosenthal/c59d77492cd45bc8a99f to your computer and use it in GitHub Desktop.
A wrapper that refreshes the inner every refresfRate
package core
import org.joda.time.DateTime
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success, Try}
class AutoRefreshingWrapper[T](refreshFunc: => Try[T], refreshRate: Duration) extends SBLogger {
@volatile
private var inner: T = refreshFunc.get
@volatile
private var lastRefreshMillis = DateTime.now.getMillis
private val refreshRateMillis = refreshRate.toMillis
def get(): T = synchronized{
val nowMillis = DateTime.now.getMillis
if((nowMillis - lastRefreshMillis) > refreshRateMillis)
refresh()
inner
}
def refresh() = {
refreshFunc match {
case Success(value) =>
inner = value
lastRefreshMillis = DateTime.now.getMillis
case Failure(e) =>
logger.warn(s"refresh failed due to $e")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment