Reputation: 4446
I need to do few requests to database and other jobs every one second. I'v used Service, Timer and AsyncTask class to do works in background. In first minutes it is ok and works without lag but after minutes it becomes slow and slower. How I can handle my jobs without this bad effect:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
performBackgroundTask.execute();
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
return Service.START_STICKY;
}
class PerformBackgroundTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... voids) {
// do database queries and other ...
return null;
}
}
I already used IntentService and AlarmManager for this and nothing changed. From the logcat the only 4 thread pool is used.
Upvotes: 0
Views: 125
Reputation: 4165
It's because of multiple AsyncTask in timer, it works perfectly when you have less AsyncTask.
Limitations of AysncTask
Before Android 1.6, the core pool size was 1 and the maximum pool size was 10. Since Android 1.6, the core pool size is 5, and the maximum pool size is 128. The size of the queue is 10 in both cases. The keep-alive timeout was 10 seconds before 2.3, and 1 second since then.
AsyncTask will only appear to execute 5/6 of your tasks. The 6th task is being queued up until one of the other tasks complete. This is a very good reason why you should not use AsyncTasks for long-running operations - it will prevent other AsyncTasks from ever running.
Solution
In this case, you should use the thread with your own thread pool executor.that will queue the task and take up the tasks base on your priorities
Upvotes: 2