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