Android:定期执行代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10207612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:52:19  来源:igfitidea点击:

Android: execute code in regular intervals

androidmultithreading

提问by Tomá? 'Guns Blazing' Fr?ek

I need to perform some code in regular intervals (connect to a server and pull data from MySQL database every minute). For this purpose I have a Sync class:

我需要定期执行一些代码(连接到服务器并每分钟从 MySQL 数据库中提取数据)。为此,我有一个 Sync 类:

public class Sync {

    static private Handler handler = new Handler();
    Runnable task;

    public Sync(Runnable task, long time) {
        this.task = task;
        handler.removeCallbacks(task);
        handler.postDelayed(task, time);
    }
}

and in my Activity I have:

在我的活动中,我有:

public void onCreate(Bundle savedInstanceState) {
    ...
    Sync sync = new Sync(call,60*1000);
    ...
}

final private Runnable call = new Runnable() {
    public void run() {
    //This is where my sync code will be, but for testing purposes I only have a Log statement
    Log.v("test","this will run every minute");
    }
};

I have tried this with a shorter time period for testing, but It only runs once. When it Logs the message for the first time, its also the last. Does anyone see what Im doing erong here? Thanks!

我已经尝试过较短的测试时间,但它只运行一次。当它第一次记录消息时,它也是最后一次。有没有人看到我在这里做什么?谢谢!

回答by MKJParekh

You can do that using the below code, Hope it helps!

你可以使用下面的代码来做到这一点,希望它有帮助!

final Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
        try{
            //do your code here
        }
        catch (Exception e) {
            // TODO: handle exception
        }
        finally{
            //also call the same runnable to call it at regular interval
            handler.postDelayed(this, 1000); 
        }
    } 
}; 

//runnable must be execute once
handler.post(runnable);

回答by Maneesh

First you have to declare handler globally Second you have to use post Delay method again in runnable to trigger it again.

首先,您必须全局声明处理程序其次,您必须在 runnable 中再次使用 post Delay 方法来再次触发它。

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Sync sync = new Sync(call,60*1000);

    }
    final private Runnable call = new Runnable() {
        public void run() {
        //This is where my sync code will be, but for testing purposes I only have a Log statement
        Log.v("test","this will run every minute");
        handler.postDelayed(call,60*1000);
        }
    };
    public final Handler handler = new Handler();
    public class Sync {


        Runnable task;

        public Sync(Runnable task, long time) {
            this.task = task;
            handler.removeCallbacks(task);
            handler.postDelayed(task, time);
        }
    }


}

回答by ScouseChris

handler.postDelayed(task, time);will only execute once, if you want the code to trigger at regular intervals I would suggest a Timerand a TimerTaskinstead of a Handlerand a Runnable.

handler.postDelayed(task, time);只会执行一次,如果您希望代码定期触发,我建议使用 aTimer和 aTimerTask而不是 aHandler和 a Runnable

TimerTaskscan be set to run once, every x seconds, or with a fixed period e.g. x seconds - however long it took to run last time.

TimerTasks可以设置为每 x 秒运行一次,或以固定的时间段运行,例如 x 秒 - 无论上次运行需要多长时间。

回答by ritesh4326

      private void doSomethingRepeatedly() {
      timer.scheduleAtFixedRate( new TimerTask() {
            public void run() {

                  try{

                   //Your code

                  }
                  catch (Exception e) {
                      // TODO: handle exception
                  }

             }
            }, 0, 10000);
                     }

回答by laffuste

An alternative way, using ScheduledExecutorService's scheduleAtFixedRate:

另一种方法,使用 ScheduledExecutorService 的scheduleAtFixedRate

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public void beepEvery10Seconds() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); }
     };
     final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 10, SECONDS);
}