I have a thread which is in charge of doing some processes. I want make it so that these processing would be done every 3 seconds. I've used the code below but when the thread starts, nothing happens.
I assumed that when I define a task for my timer it automatically execute the ScheduledTask
within time interval but it doesn't do anything at all.
What am I missing?
class temperatureUp extends Thread
{
@Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
increaserTimer.schedule(increaseTemperature, 3000);
}
};
A few errors in your code snippet:
Thread
class, which is not really good practiceTimer
within aThread
? That doesnt make sense as the aTimer
runs on its ownThread
.You should rather (when/where necessary), implement a
Runnable
see here for a short example, however I cannot see the need for both aThread
andTimer
in the snippet you gave.Please see the below example of a working
Timer
which will simply increment the counter by one each time it is called (every 3seconds):Addendum:
I did a short example of incorporating a
Thread
into the mix. So now theTimerTask
will merely incrementcounter
by 1 every 3 seconds, and theThread
will displaycounter
s value sleeping for 1 seconds every time it checks counter (it will terminate itself and the timer aftercounter==3
):In order to do something every three seconds you should use scheduleAtFixedRate (see javadoc).
However your code really does nothing because you create a thread in which you start a timer just before the thread's run stops (there is nothing more to do). When the timer (which is a single shoot one) triggers, there is no thread to interrupt (run finished before).
I think the method you've used has the signature
schedule(TimerTask task, long delay)
. So in effect you're just delaying the start time of the ONLY execution.To schedule it to run every 3 seconds you need to go with this method
schedule(TimerTask task, long delay, long period)
where the third param is used to give the period interval.You can refer the Timer class definition here to be of further help
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html