34

我需要定期执行一些代码(连接到服务器并每分钟从 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);
    }
}

在我的活动中,我有:

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");
    }
};

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

4

5 回答 5

57

您可以使用以下代码执行此操作,希望对您有所帮助!

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);
于 2012-04-18T10:44:33.833 回答
8

首先,您必须全局声明处理程序其次,您必须在 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);
        }
    }


}
于 2012-04-18T10:53:23.330 回答
3

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

TimerTasks可以设置为每 x 秒运行一次,或以固定周期(例如 x 秒)运行 - 不管上次运行所花费的时间。

于 2012-04-18T10:45:45.697 回答
1
      private void doSomethingRepeatedly() {
      timer.scheduleAtFixedRate( new TimerTask() {
            public void run() {

                  try{

                   //Your code

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

             }
            }, 0, 10000);
                     }
于 2014-02-26T13:31:44.090 回答
1

另一种方法,使用 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);
}
于 2017-09-06T15:42:04.870 回答