Created
February 1, 2018 05:30
-
-
Save mysteriouspants/d3e64798eb969175271b9783aa063afe 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
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