【问题标题】:Android CountDownTimer alternative in Spring Boot (Java)Spring Boot (Java) 中的 Android CountDownTimer 替代方案
【发布时间】:2022-01-16 19:28:53
【问题描述】:

我有这种情况,传感器的数据每 5 分钟发送一次到我的服务器。服务器将接收到的数据存储在数据库中。现在,当服务器接收到数据时,我想为这个特定的传感器启动 6 分钟计时器。如果我在这 6 分钟之前收到数据,则必须取消并重新启动此计时器。如果计时器恰好完成,则必须调用onFinish(),然后我将向用户发送有关传感器可能存在连接问题的通知。我有这个传感器列表和一个在服务器接收数据时调用的方法:

// 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()
}

我一直在研究scheduleWithFixedDelay,但这需要具有特定线程数的ExecutorService。现在,如果我有数千个传感器并且我需要同时运行这数千个计时器怎么办?

现在在 Android 中,我可以简单地使用 CountDownTimer,但由于它不是 Android,我正在寻求在 Spring Boot 环境中使用 Kotlin 解决此问题的最佳方法的建议(或者简单地说,不是在Android 环境中)。谢谢。

【问题讨论】:

    标签: java spring-boot kotlin timer


    【解决方案1】:

    您发现的ScheduledExecutorService 是未来调度任务的标准方式。您可以安排数以千计的计时器并使用单个线程全部执行 - 没问题。

    或者,如果您使用协程,您可以使用 delay()withTimeout() 等实用工具。

    另外,如果您真的打算拥有大量此类计时器,那么实施和维护替代解决方案可能会更容易,因为我们只有一个“滴答”线程/协程,每个例如检查一次所有传感器。 10 秒。它遍历所有传感器并检查上次接收数据的时间。当新数据到来时,我们只更新时间,不需要取消和重启任何定时器。

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多