长时间延迟运行

时间:2018-08-22 11:51:26

标签: java android

我正在尝试将Runnable的执行延迟很长的时间(大约几个小时)。

由于我必须更改的值仅影响UI,因此当应用程序被终止时,可运行对象不必执行。使用AlarmManager或Job会效率低下,因为如果关闭该应用,它们将重新打开该应用。

我的用例的最佳人选是Handler,但不幸的是,Runnable的执行时间没有这么长的延迟。

我还尝试了TimerScheduledThreadPoolExecutor和其他使用线程的解决方案,但是没有运气。

您对我如何实现我所需要的有想法吗?

2 个答案:

答案 0 :(得分:2)

您绝对应该看起来像AlarmManagerExecutors。我喜欢使用:

Executors.newSingleThreadScheduledExecutor()
.schedule(runnable, amount.toLong(), timeUnit)

或使用JobScheduler

JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
// You can then cancel the job in onStop():
scheduler.cancelAll(); // or a specific job

您只需要检查视图是否仍然存在即可。


还有新的WorkManager,但我还没有足够的推荐它:https://developer.android.com/reference/androidx/work/WorkManager

答案 1 :(得分:0)

我曾经做过一次..您可以将时间节省为共享首选项,当您打开应用程序时,请每次检查是否现在的时间大于您在3小时内保存的时间,然后执行功能。

希望有帮助!

相关问题