i have set a thread and i want to run it using a loop. so this thread should run in the loop and break in a certain time and again run the loop.
please i have no clue how to do this. can someone guide me.
Java has a built in mechanism for having a thread do something and then wait for a while to do it again, called Timer
. You can put what would be inside your loop inside the Run()
method of a TimerTask
, and then tell the timer how often you want it done.
TimerTask task = new TimerTask() {
@Override
public void run() {
//do some processing
}
};
Timer timer = new Timer();
timer.schedule(task, 0l, 1000l); //call the run() method at 1 second intervals
It is of course your job to shut it down when the program is done.
http://java.sun.com/javase/6/docs/api/java/util/Timer.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With