Skip to content

Instantly share code, notes, and snippets.

@mysteriouspants
Created February 1, 2018 05:30
Show Gist options
  • Save mysteriouspants/d3e64798eb969175271b9783aa063afe to your computer and use it in GitHub Desktop.
Save mysteriouspants/d3e64798eb969175271b9783aa063afe to your computer and use it in GitHub Desktop.
class ServiceClient(val userAgent: String, val rateLimit: Float = 1.0f) {
// ref https://github.com/kittinunf/Fuel
private val fuelManager = FuelManager()
private var previousDispatchTime = Instant.now()
init {
fuelManager.basePath = "https://my-service.com"
fuelManager.baseHeaders = mapOf("User-Agent" to userAgent)
fuelManager.addRequestInterceptor {
// rate-limit requests
synchronized(previousDispatchTime) {
if (Instant.now().minus(previousDispatchTime.millis).millis > (1.0 / rateLimit * 1000.0).toLong()) {
Thread.sleep((1.0 / rateLimit * 1000.0).roundToLong())
}
previousDispatchTime = Instant.now()
}
it
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment