Resettable Java Timer

前端 未结 8 1097
爱一瞬间的悲伤
爱一瞬间的悲伤 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.

提交回复
热议问题