0

i have a problem using TimerTask in android. The situation is this one:

I have a class extending AsyncTask, cal it MyAsyncTask, and i have a static method in another class, call it SchedulerClass.

SchedulerClass has this method

TimerTask myTimerTask;
public static boolean scheduleMyJob() {
        try {
            Log.i(LOG_TAG,"entered in scheduleMyJob function");

            MyAsyncTask task = new MyAsyncTask ();
            myTimerTask = new TimerTask() {

                @Override
                public void run() {
                    try {
                        _task .execute("");
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "error executing task");
                    }
                }
            };
            Timer t = new Timer();
            t.schedule(myTimerTask , 10000);
            return true;

        } catch (Exception e) {
            Log.e(LOG_TAG, "error scheduling task");
            return false;
        }
    }

and MyAsyncTask is something like this

public class MyAsyncTask extends AsyncTask<String, Integer, String> {


    @Override
    protected String doInBackground(String... params) {
             Log.i(LOG_TAG,"entered in MyAsyncTask.doInBackground method");

             //DO MY STUFF

             return "result";
        }

        @Override
    protected void onPostExecute(String result) {
           SchedulerClass.scheduleMyJob();
        }
}

This approach works fine most of the time, but sometime myTimerTask is scheduled after much more than 10 seconds: i can read the log "entered in scheduleMyJob function"but the log "entered in MyAsyncTask.doInBackground method" is written after much more than 10 seconds (which is the time used for scheduling). When I say "much more" I mean even minutes.

what's wrong? I need an accurate timing system, I can tolerate a few seconds but no minutes.

Moreover i need this scheduling being active even if the device is in standby

Thanks for any help

4

1 回答 1

0

在真实环境中,这些更新将每 10 分钟或更长时间运行一次,在我的测试中,我使用 10 秒

这要明智得多。

如果这些是我的要求,你有什么建议?

删除所有现有代码。

然后,设置AlarmManager ELAPSED_REALTIME_WAKEUP事件,绑定到我的BroadcastReceiver或你自己的/逻辑。您需要此组合以满足您的“即使设备处于待机状态,调度也处于活动状态”的要求。WakefulIntentServiceIntentServiceWakeLock

于 2013-05-13T13:15:00.563 回答