如何运行的异步任务的机器人每x分钟?机器人、任务

2023-09-12 00:49:27 作者:巴黎铁塔的承诺

如何运行在特定的时间异步任务? (我想运行它每2分钟)

how to run the async task at specific time? (I want to run it every 2 mins)

我试着使用延迟后,但它不工作?

I tried using post delayed but it's not working?

    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);

在上面的code readwebpage是函数调用异步任务对我来说..

In the above code readwebpage is function which calls the async task for me..

现在下面是我使用的方法

Right now below is the method which I am using

   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read(); 
                   //read is my another function which does the real work    
        response1=read(); 
        super.onPostExecute(response1);
        return response1;
    }


      protected void onPostExecute(String result) {


         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }

这就是我我的code是它工作完​​全正常,但大的问题,我可以释放我的电池?

This is what I my code is and it works perfectly fine but the big problem I drains my battery?

推荐答案

您可以使用处理程序,如果你想启动的东西每隔X秒。处理器是不错的,因为你并不需要额外的线程保持射击的事件时跟踪。这里是一个简短的片段:

You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:

private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
Handler mHandler;

Runnable mHandlerTask = new Runnable()
{
     @Override 
     public void run() {
          doSomething();
          mHandler.postDelayed(mHandlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    mHandlerTask.run(); 
}

void stopRepeatingTask()
{
    mHandler.removeCallbacks(mHandlerTask);
}

注意 DoSomething的应该用不了多长时间(像音频播放的UI更新位置)。如果它可能需要一些时间(如下载或上传到网上),那么你应该使用的 ScheduledExecutorService的 scheduleWithFixedDelay 函数。

Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.