I have this scenario, where data from my sensor is sent to my server every 5 minutes. The server stores received data in the database. Now when a server receives the data, I want to start 6 minutes timer for this specific sensor. If I receive data earlier than those 6 minutes, this timer must be canceled and started again. If the timer happens to finish, onFinish() must be called, which then I will send a notification to the user about a possible connection issue with the sensor. I have this list of sensors and a method that gets called when the server receives data:
// list to save sensors and their timers
private val sensors: MutableMap<Long, CountDownTimer> = HashMap()
// this method gets called after server receives data from the sensor
// must keep in mind that CountDownTimer is undefined
fun initiateTimer(sensorId: Long) {
sensors[sensorId] = object : CountDownTimer(360000, 1000) {
fun onTick(duration: Long) {
// Blank
}
fun onFinish() {
// Send notification to user about possible connection issue
}
}.start()
}
I've been looking into scheduleWithFixedDelay, but this requires ExecutorService with specific threads count. Now what if I have thousands of sensors and I need those thousand timers running at once?
Now in Android, I can simply use CountDownTimer, but since it's not Android, I am seeking advice for the best possible approach to solve this problem using Kotlin in Spring Boot environment (or in simple terms, not in Android environment). Thank you.
CodePudding user response:
ScheduledExecutorService that you found is a standard way of scheduling tasks in the future. You can schedule thousands of timers and execute them all using a single thread - no problem with that.
Alternatively, if you use coroutines, you can use utils like delay() or withTimeout().
Also, if you really plan to have a big number of such timers, then it could be easier to implement and maintain alternative solution where we only have a single "ticking" thread/coroutine that checks all sensors once per e.g. 10 seconds. It iterates over all sensors and checks when the data was received the last time. When new data arrives, we only update the time, but we don't need to cancel and restart any timers.
