我有一个要求,我需要创建一个计时器任务,每10秒后执行一次该功能。有重置Button
,点击重置Button
我想重置我的时间从10秒到30秒。现在,在执行该功能30秒后,我需要再次将计时器重置为10秒。我尝试使用Handler
,TimerTask
和CountDownTimer
,但无法达到要求。任何人都可以建议我解决这个问题的最佳方法
// OnCreate of Activity
if (timerInstance == null) {
timerInstance = Timer()
timerInstance?.schedule(createTimerTask(), 10000L, 10000L)
}
private fun createTimerTask(): TimerTask {
return object : TimerTask() {
override fun run() {
Log.d("TimerTask", "Executed")
//presenter?.onCountdownTimerFinished(adapter.activeCallList, adapter.previousPosition)
}
}
}
//On Reset Button Click
timerInstance?.cancel()
timerInstance = Timer()
timerInstance?.schedule(createTimerTask(), 30000L, 30000L)
当您按下按钮时,您可以取消提交的TimerTask
并重新安排,延迟30秒,周期为10秒? https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#scheduleAtFixedRate-java.util.TimerTask-long-long-
示例代码:
package so20190423;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
System.out.println(new Date());
Timer timer = new Timer();
TimerTask task = newTask();
timer.scheduleAtFixedRate(task, 10000L, 10000L);
task.cancel();
timer.scheduleAtFixedRate( newTask(), 30000L, 10000L);
}
protected static TimerTask newTask() {
return new TimerTask() {
@Override
public void run() {
System.out.println("YO");
System.out.println(new Date());
}
};
}
}
HTH!