How to reschedule a task using timer? How to reschedule a task using timer? multithreading multithreading

How to reschedule a task using timer?


You cannot use the same TimerTask in one or several Timer.

You need to create a new instance of the TimerTask to be executed:

t.cancel();t = new Timer();TimerTask newTask = new MyTimerTask();  // new instancet.schedule(newTask, timeDelay);


Are you sure that Timers are the way to go? It sounds like you should listen for messages with a maximum wait time. Something like this (pseudo-code);

boolean timeout = false;while (!timeout) {  // Read a message within 30 seconds  try {    Message msg = consumer.receive( 30000 );  } catch (JMSException jmse) {    timeout=true;  }  // Process the message here  process(msg);}// Timed-out while waiting for a message, so process messages in the queueprocessQueue();

Put this in a function and call it repeatedly. Wrap it inside of a Thread or Runnable if you need multi-threaded capabilities.


Reuse your Timer, and recreate your TimerTasks after cancelling them. Store tasks so that they can be cancelled later.