I have to run a bit of code in the background every one second, the code will call a webservice which searches a database and returns a value to the application. My question is which method would be the most effective to do this? I have read up on Timers, Threads, AsyncTask and Services and each seem to have their pros and cons. Please can someone tell me which would be the best to use considering execution time and battery life.
Thanks
Update:
I decided to use Aysnc task to run my code in the background while using a TimeTask to trigger the AsyncTask at regular intervals. This way the operation is destroyed when I leave that particular activity
You will have to create a new
Threadso that the call don’t lock up the device if the call takes longer than expected. TheAsyncTaskis an easy way to use multithreading, but it lacks the functionality of repeating tasks. I would say that you are best of either using aTimeror the newerScheduledExecutorService.If you chose to use the
Timeryou create aTimerTaskthat you can hand it. TheScheduledExecutorServicetakes a Runnable instead.You might want to wrap the thread in a
Service(The Service does not provide a new Thread), but this is not always necessary depending on your needs.As suggested in comment, you can also use the
Handler.postDelayed(). Although you still need to create a new thread and then callLooper.prepare()on it:(Code from Looper docs)
Also; calls to a webservice every second seems way too frequent, especially if the user is on a slow connection or there are data that needs to be transferred, try to reduce the calls as much as possible.