I need to have a background thread that constantly does an action, sleep for X seconds and do the action etc.
Basically the run method is something like:
while(!isInterrupted()){
//do something
Thread.sleep(10);
}
My question is:
- Does it make sense to use an executor in this case? Since I am not
spawning threads, is even in this case using an executor (single
threaded) better? - Additionally if I want a guarantee that the thread goes in the
dopart in exactly 10 seconds, is that possible via using
something
just a custom thread or more guaranteed via an executor? I mean if I have a hard limit of 10 seconds to perform an action, what can I do to achieve it? I assume that the time that the code goes back indo somethingmay fluctuate due to scheduling etc. How could I get such a guarantee?
If you are using only a single thread which is a forever running task like yours then you can use your present logic.
But only when you have some small tasks that need to be run, then there is point in using SingleThreadPool.
There is no such guarantee from the OS side (Linux or Windows), that the thread will return from sleep at exact 10 seconds. Try increasing thread priority, but that too is not guaranteed to work.
Your logic should not be dependent on such hard timings IMO.