Last active
November 23, 2015 13:17
-
-
Save MishaelRosenthal/c59d77492cd45bc8a99f to your computer and use it in GitHub Desktop.
A wrapper that refreshes the inner every refresfRate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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