3 回答
TA贡献1878条经验 获得超4个赞
我认为您应该使用 RxJava 和 Job Scheduler 以特定时间间隔安排任务。
例如:
Observable.interval(50, TimeUnit.SECONDS) .doOnNext(n -> performYourtask()) .subscribe();
TA贡献1895条经验 获得超3个赞
为什么不安排一次,然后自行取消?
long duration=whatever;
java.util.Timer timer = new java.util.Timer();
java.util.TimerTask task = new java.util.TimerTask() {
long t0=System.currentTimeMilis(); // or set it upon scheduling;
@Override
public void run() {
//this will stop the task from executing in future.
if((System.currentTimeMillis() - t0) >= duration) { this.cancel(); return;}
// do actual work
RemoteKey.send(PageUp);
}
};
timer.scheduleAtFixedRate(task,initialDelay,delayBetweenActions);
更现代的方法是使用ScheduledExecutorService.
TA贡献1735条经验 获得超5个赞
这将是最佳方法,使用现代ScheduledExecutor
因为时间跨度,比如 50 秒,由获取操作决定,并且该操作是同步的,您只需要等待它结束。
// Start the executor, scheduling your Runnable Task to run every 10 seconds
executorService.scheduleAtFixedRate(
() -> {
// Send your data
}, 0, 10, TimeUnit.SECONDS);
// Fetch data from your Server.
// That's a blocking operation, which, let's say will take 50 seconds
// Stop the Executor as the time is over
executorService.shutdown();
Executor可以通过工厂方法创建。
Executors.newScheduledThreadPool(5); // For multiple, concurrent threads
Executors.newSingleThreadScheduledExecutor(); // For a synchronous "queue"
添加回答
举报