I have a periodic action which I want to do in a defined intervall (granularity in seconds). So I used a thread which sleeps for the requested time and then do the action and then sleep again and so on..
public class DiscoveryThread extends Thread
{
private int deviceDiscoveryIntervall = 1;
public void setDeviceDiscoveryIntervall(int seconds)
{
deviceDiscoveryIntervall = seconds;
}
@Override
public void run()
{
while(!isInterrupted())
{
//do there the action
try
{
sleep(deviceDiscoveryIntervall*1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now I want to set sometimes a new intervall for the periodic action. If the intervall was before 10 seconds and I set it 5 seconds after the last action to one second, I have to wait anyway 5 seconds until the next action, but It should do the action in this case immediately.
So how should I do this? If I use the interrupted()
method, the sleep method will throw an InterruptedException
and I could do the action immediately. But then I have to use an own flag for the whole loop as I don't want to exit the thread. And how is about calling the sleep()
method again after an InterruptedException
, is the interrupted flag still set? Am I able to interrupt the sleep()
method again? And how about using the interrupted() method for not stopping the thread, is this not kind of missusing it?