Mah*_*oud 5 multithreading android android-handler
我正在开发一个应用程序,它要求它每隔x分钟上线并检查一些新数据.为防止繁重的网络和数据使用,任务应以固定速率运行,但这种解决方案的最佳使用方法是什么?一个Handler或一个Timer对象?
使用 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)
| 归档时间: |
|
| 查看次数: |
2062 次 |
| 最近记录: |