Last active
March 18, 2018 17:18
-
-
Save JohnMurray/a18c71fc1ff55356dac5c647b0eb3f50 to your computer and use it in GitHub Desktop.
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
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