如何在一定时间后停止计时器? [英] How to stop the timer after certain time?

查看:265
本文介绍了如何在一定时间后停止计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序,它有一个运行任务的计时器:

I have an android application which has a timer to run a task:

time2.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            sendSamples();
        }
    }, sampling_interval, sending_interval);

让我们说sampling_interval是2000而sending_interval是4000.

Lets say sampling_interval is 2000 and sending_interval is 4000.

所以在这个应用程序中,我将一些读数值从传感器发送到服务器。但我想在10000(10秒)后停止发送。

So in this application I send some reading values from a sensor to the server. But I want to stop the sending after 10000 (10 seconds).

我该怎么办?

推荐答案

尝试

        time2.scheduleAtFixedRate(new TimerTask() {
            long t0 = System.currentTimeMillis();
            @Override
            public void run() {
              if (System.currentTimeMillis() - t0 > 10 * 1000) {
                  cancel();
              } else {
                  sendSamples();
              }
            }
...

这篇关于如何在一定时间后停止计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆