Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – 用于调度固定速率任务的处理程序或计时器大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个应用程序,它要求它每隔x分钟上线并检查一些新数据.为防止繁重的网络和数据使用,任务应以固定速率运行,但这种解决方案的最佳使用方法是什么?处理程序或计时器对象?

解决方法@H_489_4@
使用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 (),duration,TimeUnit.MICROSECONDS);
long delay = 100; //the delay between the termination of one execution and the commencement of the next
exec.scheduleWithFixedDelay(new myTask(),TimeUnit.MICROSECONDS);

并取消执行者使用此 – ScheduledFuture

// schedule long running task in 2 minutes:
scheduledFuture scheduleFuture = exec.scheduleAtFixedRate(new myTask(),TimeUnit.MICROSECONDS);

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

大佬总结

以上是大佬教程为你收集整理的android – 用于调度固定速率任务的处理程序或计时器全部内容,希望文章能够帮你解决android – 用于调度固定速率任务的处理程序或计时器所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。