6

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);

Lets say sampling_interval is 2000 and sending_interval is 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).

What should I do?

Sufian
  • 6,405
  • 16
  • 66
  • 120
secret
  • 746
  • 2
  • 14
  • 28
  • 1
    http://stackoverflow.com/questions/11489988/how-to-stop-a-timer-after-certain-number-of-times – thar45 Apr 09 '13 at 06:41

1 Answers1

9

try

        time2.scheduleAtFixedRate(new TimerTask() {
            long t0 = System.currentTimeMillis();
            @Override
            public void run() {
              if (System.currentTimeMillis() - t0 > 10 * 1000) {
                  cancel();
              } else {
                  sendSamples();
              }
            }
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • One thing to consider is if sendSamples() can take longer than one scheduling interval, and if it does, how do you want the code to work. If you want 10 iterations regardless, then use a counter instead of `currentTimeMillis`. If you want it to not start again after that much time has passed, this is a good solution. – ash Aug 28 '13 at 04:15