Resettable Java Timer

前端 未结 8 1077
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 07:31

I\'d like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer wa

相关标签:
8条回答
  • 2020-11-28 08:13

    If your Timer is only ever going to have one task to execute then I would suggest subclassing it:

    import java.util.Timer;
    import java.util.TimerTask;
    
    public class ReschedulableTimer extends Timer
    {
        private Runnable  task;
        private TimerTask timerTask;
    
        public void schedule(Runnable runnable, long delay)
        {
            task = runnable;
            timerTask = new TimerTask()
            {
                @Override
                public void run()
                {
                    task.run();
                }
            };
            this.schedule(timerTask, delay);
        }
    
        public void reschedule(long delay)
        {
            timerTask.cancel();
            timerTask = new TimerTask()
            {
                @Override
                public void run()
                {
                    task.run();
                }
            };
            this.schedule(timerTask, delay);
        }
    }
    

    You will need to work on the code to add checks for mis-use, but it should achieve what you want. The ScheduledThreadPoolExecutor does not seem to have built in support for rescheduling existing tasks either, but a similar approach should work there as well.

    0 讨论(0)
  • 2020-11-28 08:17

    this is what I'm trying out. I have a class that polls a database every 60 seconds using a TimerTask.

    in my main class, I keep the instance of the Timer, and an instance of my local subclass of TimerTask. the main class has a method to set the polling interval (say going from 60 to 30). in it, i cancel my TimerTask (which is my subclass, where I overwrote the cancel() method to do some cleanup, but that shouldn't matter) and then make it null. i recreate a new instance of it, and schedule the new instance at the new interval in the existing Timer.

    since the Timer itself isn't canceled, the thread it was using stays active (and so would any other TimerTasks inside it), and the old TimerTask is replaced with a new one, which happens to be the same, but VIRGIN (since the old one would have been executed or scheduled, it is no longer VIRGIN, as required for scheduling).

    when i want to shutdown the entire timer, i cancel and null the TimerTask (same as i did when changing the timing, again, for cleaning up resources in my subclass of TimerTask), and then i cancel and null the Timer itself.

    0 讨论(0)
提交回复
热议问题