How to pause/resume or change the period time of TimerTask?

强颜欢笑 提交于 2019-12-11 09:58:40

问题


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 - Once the timer is pause, you have to re-new another one. So do the TimerTask.

  2. 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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/10347155/how-to-pause-resume-or-change-the-period-time-of-timertask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!