How to pause/resume or change the period time of T

2019-07-24 14:48发布

问题:

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.