一段时间后,AsyncTask的服务速度变慢



我需要每隔一秒钟对数据库和其他作业进行少量请求。我使用了Service、Timer和AsyncTask类在后台进行工作。在最初的几分钟里,它还可以,工作没有滞后,但几分钟后,它变得越来越慢。我如何在没有这种不良影响的情况下处理我的工作:

@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;
}
}

我已经为此使用了IntentService和AlarmManager,但没有任何更改。从logcat中,只使用了4个线程池。

这是因为计时器中有多个AsyncTask,所以当AsyncTask较少时,它可以完美工作。

AysncTask的限制

在Android 1.6之前,核心池大小为1,最大池大小为10。自Android 1.6以来,核心池大小为5,最大池大小为128。在这两种情况下,队列的大小都是10。保活超时在2.3之前是10秒,之后是1秒。

AsyncTask将只显示为执行您的5/6个任务。第6个任务正在排队,直到其他任务之一完成。这就是为什么不应该将AsyncTasks用于长时间运行的操作的一个很好的理由——这将阻止其他AsyncTasks运行。

解决方案

在这种情况下,您应该将线程与自己的线程池执行器一起使用。这将根据您的优先级对任务进行排队并占用任务

最新更新