简体   繁体   English

如何在一定时间后停止计时器?

[英]How to stop the timer after certain time?

I have an android application which has a timer to run a task: 我有一个Android应用程序,它有一个计时器来运行任务:

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

Lets say sampling_interval is 2000 and sending_interval is 4000. 让我们说sampling_interval是2000,sending_interval是4000。

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). 但我想在10000(10秒)后停止发送。

What should I do? 我该怎么办?

try 尝试

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

Check this code: 检查此代码:

private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
    private int counter = 0;
    public void run() {
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        if(++counter == 4) {
            timer.cancel();
        }
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer.schedule(task, DELAY, DELAY);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM