【问题标题】:How to run timer for each 15 seconds and to cancel it and restart it again如何每 15 秒运行一次计时器并取消它并重新启动它
【发布时间】:2015-08-19 07:17:32
【问题描述】:

我的应用中有一个条件,那就是如何控制计时器。我想要的是在恰好 15 秒后它启动并启动函数,这意味着它应该被取消,并且随着函数结束,它会从零重新开始。

到目前为止我所做的是使用计时器,并给它 1500 次延迟和 15 次重复,但它一次又一次地启动该功能,我认为我在这一行做错了:

timer.schedule(doAsynchronousTask, 1500,1 );

这是我完整的计时器代码

    private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {

    public void run() {
        handler.post(new Runnable() {
            public void run() {
                launchFunction();
            }
        });

    }
};
timer.schedule(doAsynchronousTask, 1500,1 );


void launchFunction(){

     Log.d("timer","running");
     timer.cancel();
}

但它没有按预期工作,请帮助我。

【问题讨论】:

  • 试试timer.schedule(doAsynchronousTask, 1500,1500 );
  • 第三个参数表示下次执行的周期。这意味着在第一次延迟后的每一毫秒调用该方法。
  • 它对我没有帮助,它每隔一秒就会启动该功能
  • 参数以毫秒为单位。 IE。 1000 毫秒 1 秒。所以你要写15000 15秒。
  • 第一个参数是你要启动的异步任务。第二个参数是第一次执行任务之前的初始延迟。第三个——如上所述——是两次执行之间的时间段。描述:延迟 -> 任务 任务 任务 ...

标签: java android multithreading timer


【解决方案1】:

阅读文档

/**
     * Schedule a task for repeated fixed-delay execution after a specific delay.
     *
     * @param task
     *            the task to schedule.
     * @param delay
     *            amount of time in milliseconds before first execution.
     * @param period
     *            amount of time in milliseconds between subsequent executions.
     * @throws IllegalArgumentException
     *                if {@code delay < 0} or {@code period <= 0}.
     * @throws IllegalStateException
     *                if the {@code Timer} has been canceled, or if the task has been
     *                scheduled or canceled.
     */
    public void schedule(TimerTask task, long delay, long period) {
        if (delay < 0 || period <= 0) {
            throw new IllegalArgumentException();
        }
        scheduleImpl(task, delay, period, false);
    }

将您的日程设置为timer.schedule(doAsynchronousTask, 15000,15000 ); 和 如果达到 15 次,则维护一个计数器进行计数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多