<p>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 was created and X seconds, then the event occurs as normal. </p>

<p>If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds.
 E.g. the timer should be able to do something like:</p>

<pre><code>Timer timer = new Timer();  
timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X)

//At some point between 0 and 5000 ms...  
setNewTime(timer, 8000);  //timerTask will fire in 8000ms from NOW (Y).
</code></pre>

<p>I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again.</p>

<p>The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: </p>

<pre><code>timer.stop();
timer = new Timer(8000, ActionListener);
timer.start();
</code></pre>

<p>Is there an easier way??</p>

[{'answer_id': 32008, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 1, 'selected': False, 'text': '<p>Do you need to schedule a recurring task? In that case I recommend you consider using <a href="http://opensymphony.com/quartz/" rel="nofollow noreferrer">Quartz</a>.</p>\n'}, {'answer_id': 32047, 'author': 'WMR', 'author_id': 2844, 'author_profile': 'https://Stackoverflow.com/users/2844', 'pm_score': 1, 'selected': False, 'text': "<p>I don't think it's possible to do it with <code>Timer/TimerTask</code>, but depending on what exactly you want to achieve you might be happy with using <code>java.util.concurrent.ScheduledThreadPoolExecutor</code>.</p>\n"}, {'answer_id': 32057, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 7, 'selected': True, 'text': '<p>According to the <a href="http://java.sun.com/javase/6/docs/api/java/util/Timer.html" rel="noreferrer"><code>Timer</code></a> documentation, in Java 1.5 onwards, you should prefer the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html" rel="noreferrer"><code>ScheduledThreadPoolExecutor</code></a> instead. (You may like to create this executor using <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html" rel="noreferrer"><code>Executors</code></a><code>.newSingleThreadScheduledExecutor()</code> for ease of use; it creates something much like a <code>Timer</code>.)</p>\n\n<p>The cool thing is, when you schedule a task (by calling <code>schedule()</code>), it returns a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledFuture.html" rel="noreferrer"><code>ScheduledFuture</code></a> object. You can use this to cancel the scheduled task. You\'re then free to submit a new task with a different triggering time.</p>\n\n<p>ETA: The <code>Timer</code> documentation linked to doesn\'t say anything about <code>ScheduledThreadPoolExecutor</code>, however the <a href="http://openjdk.java.net/" rel="noreferrer">OpenJDK</a> version had this to say:</p>\n\n<blockquote>\n  <p>Java 5.0 introduced the <code>java.util.concurrent</code> package and\n  one of the concurrency utilities therein is the \n  <code>ScheduledThreadPoolExecutor</code> which is a thread pool for repeatedly\n  executing tasks at a given rate or delay.  It is effectively a more\n  versatile replacement for the <code>Timer</code>/<code>TimerTask</code>\n  combination, as it allows multiple service threads, accepts various\n  time units, and doesn\'t require subclassing <code>TimerTask</code> (just\n  implement <code>Runnable</code>).  Configuring\n  <code>ScheduledThreadPoolExecutor</code> with one thread makes it equivalent to\n  <code>Timer</code>.</p>\n</blockquote>\n'}, {'answer_id': 32073, 'author': 'David Sykes', 'author_id': 3154, 'author_profile': 'https://Stackoverflow.com/users/3154', 'pm_score': 4, 'selected': False, 'text': '<p>If your <code>Timer</code> is only ever going to have one task to execute then I would suggest subclassing it:</p>\n\n<pre><code>import java.util.Timer;\nimport java.util.TimerTask;\n\npublic class ReschedulableTimer extends Timer\n{\n    private Runnable  task;\n    private TimerTask timerTask;\n\n    public void schedule(Runnable runnable, long delay)\n    {\n        task = runnable;\n        timerTask = new TimerTask()\n        {\n            @Override\n            public void run()\n            {\n                task.run();\n            }\n        };\n        this.schedule(timerTask, delay);\n    }\n\n    public void reschedule(long delay)\n    {\n        timerTask.cancel();\n        timerTask = new TimerTask()\n        {\n            @Override\n            public void run()\n            {\n                task.run();\n            }\n        };\n        this.schedule(timerTask, delay);\n    }\n}\n</code></pre>\n\n<p>You will need to work on the code to add checks for mis-use, but it  should achieve what you want. The <code>ScheduledThreadPoolExecutor</code> does not seem to have built in support for rescheduling existing tasks either, but a similar approach should work there as well.</p>\n'}, {'answer_id': 756285, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>this is what I'm trying out.  I have a class that polls a database every 60 seconds using a TimerTask.</p>\n\n<p>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.</p>\n\n<p>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).</p>\n\n<p>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.</p>\n"}, {'answer_id': 13583445, 'author': 'Shaik Khader', 'author_id': 1021549, 'author_profile': 'https://Stackoverflow.com/users/1021549', 'pm_score': 2, 'selected': False, 'text': '<p>The whole Code snippet goes like this .... I hope it will be help full</p>\n\n<pre><code>{\n\n        Runnable r = new ScheduleTask();\n        ReschedulableTimer rescheduleTimer = new ReschedulableTimer();\n        rescheduleTimer.schedule(r, 10*1000);\n\n\n    public class ScheduleTask implements Runnable {\n        public void run() {\n            //Do schecule task\n\n        }\n      }\n\n\nclass ReschedulableTimer extends Timer {\n        private Runnable task;\n        private TimerTask timerTask;\n\n        public void schedule(Runnable runnable, long delay) {\n          task = runnable;\n          timerTask = new TimerTask() { \n              public void run() { \n                  task.run(); \n                  }\n              };\n\n          timer.schedule(timerTask, delay);        \n        }\n\n        public void reschedule(long delay) {\n            System.out.println("rescheduling after seconds "+delay);\n          timerTask.cancel();\n          timerTask = new TimerTask() { \n              public void run() { \n                  task.run(); \n              }\n          };\n          timer.schedule(timerTask, delay);        \n        }\n      }\n\n\n}\n</code></pre>\n'}, {'answer_id': 13720407, 'author': 'Human Being', 'author_id': 1835198, 'author_profile': 'https://Stackoverflow.com/users/1835198', 'pm_score': 0, 'selected': False, 'text': '<p>Here is the example for Resetable Timer . Try to change it for your convinence...</p>\n\n<pre><code>package com.tps.ProjectTasks.TimeThread;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\n/**\n * Simple demo that uses java.util.Timer to schedule a task to execute\n * every 5 seconds and have a delay if you give any input in console.\n */\n\npublic class DateThreadSheduler extends Thread {  \n    Timer timer;\n    BufferedReader br ;\n    String data = null;\n    Date dNow ;\n    SimpleDateFormat ft;\n\n    public DateThreadSheduler() {\n\n        timer = new Timer();\n        timer.schedule(new RemindTask(), 0, 5*1000); \n        br = new BufferedReader(new InputStreamReader(System.in));\n        start();\n    }\n\n    public void run(){\n\n        while(true){\n            try {\n                data =br.readLine();\n                if(data != null &amp;&amp; !data.trim().equals("") ){\n                    timer.cancel();\n                    timer = new Timer();\n                    dNow = new Date( );\n                    ft = new SimpleDateFormat ("E yyyy.MM.dd \'at\' hh:mm:ss a zzz");\n                    System.out.println("Modified Current Date ------&gt; " + ft.format(dNow));\n                    timer.schedule(new RemindTask(), 5*1000 , 5*1000);\n                }\n\n            }catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n\n    public static void main(String args[]) {\n        System.out.format("Printint the time and date was started...\\n");\n        new DateThreadSheduler();\n    }\n}\n\nclass RemindTask extends TimerTask {\n    Date dNow ;\n    SimpleDateFormat ft;\n\n    public void run() {\n\n        dNow = new Date();\n        ft = new SimpleDateFormat ("E yyyy.MM.dd \'at\' hh:mm:ss a zzz");\n        System.out.println("Current Date: " + ft.format(dNow));\n    }\n}\n</code></pre>\n\n<p>This example prints the current date and time for every 5 seconds...But if you give any input in console the timer will be delayed to perform the given input task...</p>\n'}, {'answer_id': 51446933, 'author': 'luke8800gts', 'author_id': 5392548, 'author_profile': 'https://Stackoverflow.com/users/5392548', 'pm_score': 0, 'selected': False, 'text': '<p>I made an own timer class for a similar purpose; feel free to use it:</p>\n\n<pre><code>public class ReschedulableTimer extends Timer {\n  private Runnable mTask;\n  private TimerTask mTimerTask;\n\n  public ReschedulableTimer(Runnable runnable) {\n    this.mTask = runnable;\n  }\n\n  public void schedule(long delay) {\n    if (mTimerTask != null)\n      mTimerTask.cancel();\n\n    mTimerTask = new TimerTask() {\n      @Override\n      public void run() {\n        mTask.run();\n      }\n    };\n    this.schedule(mTimerTask, delay);\n  }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/32001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142/']