I need a polling thread to perform some network operations every 5 mins. I came up with the following two solution. Which would be better and why? I am looking to have minimum cpu and battery usage.
pollThread = new Thread(){
public void run(){
while(toggle) {
// Do stuff
sleep(FIVE_MINUTES);
}
}
};
pollThread.start();
OR
Runnable doStuffRunnable = new Runnable() {
@Override
public void run() {
// Do stuff
handler.postDelayed(this, FIVE_MINUTES);
}
}
The answer depends on whether you are using the Handler to handle other tasks as well. If not, there won't be much difference; there will still be a thread that wakes up every 5 minutes to do what you want. If the handler also handles other tasks, using the handler is likely to be more efficient than having a separate thread for each task, as it requires only one thread, and may have optimizations with respect to processor usage.