Skip to content

Instantly share code, notes, and snippets.

@lfmunoz
Last active September 27, 2019 15:19
Show Gist options
  • Save lfmunoz/d9a9b76ff5a9c4393214fad715f4e5b9 to your computer and use it in GitHub Desktop.
Save lfmunoz/d9a9b76ff5a9c4393214fad715f4e5b9 to your computer and use it in GitHub Desktop.
TaskDecider
import kotlin.random.Random
/**
* This class holds state about when a task was last
* executed and helps determining if it should execute again or not
* depending on configuration and the current time
*/
class TaskDecider(
private val taskIntervalMillis: Long,
private val task: () -> Unit = {}
) {
var lastExecution: Long =
if (taskIntervalMillis > 1) {
System.currentTimeMillis() - Random.nextLong(taskIntervalMillis)
} else {
0
}
fun checkAndExecute() : Boolean {
// Important: Never execute if taskInterval wasn't set to a positive number
if(taskIntervalMillis < 1) return false
val now = System.currentTimeMillis()
val delta = now - lastExecution
if (delta >= taskIntervalMillis) {
lastExecution = now
task()
return true
}
println("delta = $delta, taskIntervalMillis = $taskIntervalMillis")
return false
}
}
import kotlinx.coroutines.delay
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import kotlin.random.Random
import kotlinx.coroutines.launch
/**
* Unit Test - TaskDecider
*/
class TaskDeciderUnitTest {
val LARGEST_LONG = 1_000L
val cPool = newFixedThreadPoolContext( 4, "testPool")
@Test
fun `should never execute if taskInterval is less than or equal to 1`() {
var taskDecider = TaskDecider(0)
assertThat(taskDecider.checkAndExecute()).isFalse()
taskDecider = TaskDecider(-1)
assertThat(taskDecider.checkAndExecute()).isFalse()
taskDecider = TaskDecider(-5)
assertThat(taskDecider.checkAndExecute()).isFalse()
}
@Test
fun `execute if taskInterval greater than or equal to 1`() {
runBlocking(cPool) {
repeat(1000) {
launch {
val randomValue = Random.nextLong(2, LARGEST_LONG)
val taskDecider = TaskDecider(randomValue)
delay(randomValue)
val result = taskDecider.checkAndExecute()
assertThat(result).isTrue()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment