如何暂停/恢复或更改TimerTask的周期时间? [英] How to pause/resume or change the period time of TimerTask?

查看:388
本文介绍了如何暂停/恢复或更改TimerTask的周期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的原始目的是每xx个TimeUnit执行一段代码,而不必简​​单地循环它并检查标志.我进行了一些研究,找到了两种解决方案:

my original purpose is to execute a section of code every xx TimeUnit without simply looping it and checking a flag. I do some researches and found two solution:

  1. Timer + TimerTask-计时器暂停后,您必须重新更新另一个计时器. TimerTask也是如此.

  1. Timer + TimerTask - Once the timer is pause, you have to re-new another one. So do the TimerTask.

ScheduledThreadPoolExecutor + Runnable-与先前的组合相同.但是有人说这是增强的.但是它仍然不提供我之前提到的功能.

ScheduledThreadPoolExecutor + Runnable - The same as the previous combination. But somebody say this is a enhanced one. But it still don't provide the functions I mentioned before.

现在,我正在寻找一种解决该问题的优雅方法.也许我应该专注于锁?

Now, I'm looking for a elegant method to solove this problem. Maybe I should focus on the locks?

推荐答案

我将使用ScheduledExecutorService并使用Future.cancel()挂起.然后scheduleAtFixedRate重新启动它.

I would use the ScheduledExecutorService and use Future.cancel() to suspend. and scheduleAtFixedRate to start it again.

如果要更改时间段,请取消为,并假设未暂停该时间段,然后重新添加新的时间段.

If you want to change the period, cancel is and add it again with the new period, assuming its not suspended.

如果要隐藏此详细信息,则可以使用suspend(),resume()和setPeriod()方法创建包装器.

If you want to hide this detail you can create a wrapper with a suspend(), resume() and setPeriod() methods.

这篇关于如何暂停/恢复或更改TimerTask的周期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆