用于调度固定速率任务的处理程序或计时器

Mah*_*oud 5 multithreading android android-handler

我正在开发一个应用程序,它要求它每隔x分钟上线并检查一些新数据.为防止繁重的网络和数据使用,任务应以固定速率运行,但这种解决方案的最佳使用方法是什么?一个Handler或一个Timer对象?

Akh*_*ain 5

使用 Timer 有一些缺点

  • 它只创建一个线程来执行任务,如果一个任务运行时间太长,其他任务就会受到影响。
  • 它不处理任务抛出的异常,线程只是终止,这会影响其他计划任务并且它们永远不会运行。

而另一方面,ScheduledThreadPoolExecutor正确处理所有这些问题,使用 Timer 没有意义.. 有两种方法可以用于您的情况

  • scheduleAtFixedRate(...)

  • scheduleWithFixedDelay(..)

    class LongRunningTask implements Runnable {
    
      @Override
      public void run() {
        System.out.println("Hello world");
      } 
    }
    
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    long period = 100; // the period between successive executions
    exec.scheduleAtFixedRate(new LongRunningTask (), 0, duration, TimeUnit.MICROSECONDS);
    long delay = 100; //the delay between the termination of one execution and the commencement of the next
    exec.scheduleWithFixedDelay(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
    
    Run Code Online (Sandbox Code Playgroud)

并取消 Executor 使用此 - ScheduledFuture

// schedule long running task in 2 minutes:
ScheduledFuture scheduleFuture = exec.scheduleAtFixedRate(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);

... ...
// At some point in the future, if you want to cancel scheduled task:
scheduleFuture.cancel(true);
Run Code Online (Sandbox Code Playgroud)


Gen*_* S. 0

您应该使用像这样的服务和 AlarmReceiver 这就是它们的用途。如果您在 Activity 中使用计时器或任何其他机制,并且将数据设置为每“几分钟”更新一次,那么用户很可能不会在您的应用程序中,并且 Android 很可能会清理它,从而使您的应用程序*不存在更新。警报将保持开启状态,直到设备关闭。