periodically doing a task inside run method of a thread

periodically doing a task inside run method of a thread

Post by wanwa » Sun, 26 Feb 2006 06:40:01


I need to have a task repeated periodically in a thread . for now I'm
using inside the run method :

long pausetime = 2000;
long p = System.currentTimeMillis();
long q;
while(true){
if (p < (q = System.currentTimeMillis() - pausetime)) {
p = q + pausetime;

// modify this object's variables
}

}
// do something


I think this approach is bad because the looped if statement requires
too much work as I increase the number of threads.

I can't use sleep() of Timer object because I'm not calling from
outside the thread. Or if it's possible to use them inside the run
method, I don't know how to do it.

Please help.
 
 
 

periodically doing a task inside run method of a thread

Post by wanwa » Sun, 26 Feb 2006 06:55:18

haha, i'm so sorry. I found my error

 
 
 

periodically doing a task inside run method of a thread

Post by Oliver Won » Sun, 26 Feb 2006 06:56:20


[...]

See http://www.yqcomputer.com/

<quote>
A facility for threads to schedule tasks for future execution in a
background thread. Tasks may be scheduled for one-time execution, or for
repeated execution at regular intervals.
</quote>

You'll probably want to use this constructor:

<quote>
schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution,
beginning after the specified delay.
</quote>

Which means you'll probably want to read the JavaDocs for TimerTask:
http://www.yqcomputer.com/

- Oliver
 
 
 

periodically doing a task inside run method of a thread

Post by James McGi » Sun, 26 Feb 2006 06:58:37


Busy wait loop is never good if performance is an issue.



You should be able to use sleep() inside the run() method. See this
example from Sun that does exactly that:

http://www.yqcomputer.com/


And I'll take your word for it, but I'm sure I'd try to find a way to
make it a TimerTask and use java.util.Timer on it somehow.