Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active March 18, 2018 17:18
Show Gist options
  • Save JohnMurray/a18c71fc1ff55356dac5c647b0eb3f50 to your computer and use it in GitHub Desktop.
Save JohnMurray/a18c71fc1ff55356dac5c647b0eb3f50 to your computer and use it in GitHub Desktop.
import java.util.concurrent.{ScheduledThreadPoolExecutor, ScheduledFuture, TimeUnit}
import java.time.temporal.ChronoUnit
class ApiService[T](limit: Long, timeFrame: FiniteDuration) {
// previous code ...
private val timerPool = new ScheduledThreadPoolExecutor(1)
@volatile private var recheckFut: Option[ScheduledFuture[_]] = None
private def tryRequest(): Unit = this.synchronized {
if (hasCapacity()) {
if (recheckFut.isDefined) {
recheckFut.map(_.cancel(true))
recheckFut = None
}
makeRequest()
} else if (recheckFut.isEmpty) {
val timeRemaining = ChronoUnit.NANOS.between(LocalDateTime.now(), windowStopTime)
recheckFut = Some(timerPool.schedule(
(() => {
recheckFut = None
tryRequest()
}): Runnable,
timeRemaining,
TimeUnit.NANOSECONDS
))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment