设置多次执行任务的计时器

问题描述 投票:-1回答:1

我有一个要求,我需要创建一个计时器任务,每10秒后执行一次该功能。有重置Button,点击重置Button我想重置我的时间从10秒到30秒。现在,在执行该功能30秒后,我需要再次将计时器重置为10秒。我尝试使用HandlerTimerTaskCountDownTimer,但无法达到要求。任何人都可以建议我解决这个问题的最佳方法

// 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)
java android handler countdowntimer timertask
1个回答
1
投票

当您按下按钮时,您可以取消提交的TimerTask并重新安排,延迟30秒,周期为10秒? https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#scheduleAtFixedRate-java.util.TimerTask-long-long-

  1. 通过调用.cancel取消第一个提交的任务。
  2. 在按钮上按计划使用30000L,10000L作为延迟和周期

示例代码:

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!

© www.soinside.com 2019 - 2024. All rights reserved.