Created
January 11, 2020 13:57
-
-
Save DevSrSouza/bd3e2b2061430fd28d0e0bb60c84137a to your computer and use it in GitHub Desktop.
Take max milliseconds time to do a work and wait to continue doing.
This file contains 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 br.com.devsrsouza.kotlinbukkitapi.controllers | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.runBlocking | |
import java.util.concurrent.ConcurrentHashMap | |
import kotlin.coroutines.CoroutineContext | |
import kotlin.coroutines.coroutineContext | |
import kotlin.system.measureTimeMillis | |
fun main() { | |
runBlocking { | |
val time = measureTimeMillis { | |
for (i in 1..50) { | |
print(i) | |
takeMaxMilliseconds(50) | |
delay(10) | |
} | |
} | |
println(time) | |
} | |
} | |
data class TakeValues(val startTimeMiliseconds: Long, val takeTime: Long) | |
private val takes = ConcurrentHashMap<CoroutineContext, TakeValues>() | |
suspend fun takeMaxMilliseconds(millisecond: Long, waitTime: Long = 1000) { | |
val takeValues = takes.get(coroutineContext) | |
if(takeValues == null) { | |
// registering take max at current millisecond | |
takes.put(coroutineContext, TakeValues(System.currentTimeMillis(), millisecond)) | |
} else { | |
val exceededTime = System.currentTimeMillis() - takeValues.startTimeMiliseconds - takeValues.takeTime | |
// checking if this exceeded the max time of execution | |
if(exceededTime >= 0) { | |
takes.remove(coroutineContext) | |
delay(waitTime) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment