How to synchronize android Handlers with different intervals?

时间:2019-01-18 18:43:28

标签: android android-service android-handler

I have two handlers running within an Android Service.

  • handler1 runs every 30 seconds
  • handler2 runs every 5 seconds

The problem is, handler2 can't run at the same time as handler1.

I mean, when handler2 reaches 30, 60, 90... secs it will run at the same time as handler1.

So, I need to find a way during those 30, 60 90 secs to run one handler after another.

I know a solution for this could be, but it's not elegant, neither accurate:

  • Run handler1 at second 0
  • Wait 7 seconds (or any other x # of secs no-multiple of 5)

3 个答案:

答案 0 :(得分:0)

In order to make sure that handler1 always runs before handler2, you can use the following approach:

Each time that handler1 has finished what it's supposed to do, it will [fire a signal to the Service in which both Handlers are running to] start handler2 immediately.

handler2 (or the Service) will be allowed to schedule the repeated execution of the Runnable for the next five rounds. You can use some type of countdown to keep track of the remaining rounds. The last "independently-managed" round will be started approximately 25 seconds after the initial round. After this round, it's up to handler1 to issue the next start command for handler2.

答案 1 :(得分:0)

由于处理程序2的运行频率比处理程序1的运行频率高,因此您可以在处理程序2中使用计数器来跟踪何时触发计划在处理程序1中触发的事件。

.dll

答案 2 :(得分:0)

如何使用TimerTaskTimer安排重复执行(每5秒一次)?根据时间间隔,您可以运行handler1中当前完成的工作,或者运行handler2中完成的工作,或同时运行这两项。也许您可以将这些作业分解为从TimerTask's run方法调用的函数。这样一来,handler1作业就可以在同一线程上以同步方式在handler2作业之前运行。