java - 让 countDownTimer 立即执行,然后每 x 秒执行一次
问题描述
我有一个 countDownTimer 在单击按钮时每 10 秒执行一次代码的某个部分。但它只在单击按钮后 10 秒执行代码。我如何让它立即执行,然后每隔一秒执行一次?
CountDownTimer countDown;
public void onButtonClick (View v) throws IOException, InterruptedException {
countDown = new CountDownTimer(10000,10000)
{
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
start();
//codes
}.start();
}
}
解决方案
如果你想每 10 秒执行一次代码,我建议你做点别的。
执行 startRepeatingTask(); 单击按钮时。
private int interval = 10000; //every 10 seconds
private Handler handler;
Runnable codeExecuter = new Runnable() {
@Override
public void run() {
try {
//run your code
} finally {
handler.postDelayed(codeExecuter, interval);
}
}
};
void startRepeatingTask() {
codeExecuter.run();
}
void stopRepeatingTask() {
handler.removeCallbacks(codeExecuter);
}