0

how can i put a timer/timeout so that whenever a method is executed, there should be like 1 minute before it can be executed again. Example

if (A>B){
Toast.makeText(getApplicationContext(), "Text HERE", Toast.LENGTH_SHORT).show();
}

I dont want the toast to be spammed. So that if the condition is always satisfied, it will only show the toast every 1 minute.

Thanks!

4 Answers4

2

You can record the time at which you last did that operation, and decline to do it again if not enough time has elapsed.

For example:

 private long lastRunTime = 0;
 void maybeDoSomething() {
     long now = System.currentTimeMillis();
     if ((now-lastRunTime) > (60 * 1000)) {
        //do something here
        lastRunTime = now;
     }
 }

System.currentTimeMillis() is a reasonable short-term time source, for longer timeouts you may want to investigate other clocks.

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117
1

You can just check against the current time.

Set a variable when the method is run and check against it when the condition is true

if (A>B && System.currentTimeMillis() > interal){
    Toast.makeText(getApplicationContext(), "Text HERE", Toast.LENGTH_SHORT).show();
    interval = System.currentTimeMillis() + 6000;   // this should add 1 minute to the current time
}

make interval a long and a member variable...probably initialized to 0.

codeMagic
  • 44,549
  • 13
  • 77
  • 93
0

Use Handler in android to do some task after specific time...below code will do some task after 5000ms. You can specify code for task inside run() method of Runnable Class.

    boolean methodRunnable = true;

    if(methodRunnale){
        // Run method 
        doSomeTask();
    }else{
       //Wait for 1 minute
    }

    void doSomeTask(){
        methodRunnable = false;

        Handler handler = new Handler();
        Runnable r = new Runnable() {
        public void run() {
           methodRunnable = true;
        }
    };
    handler.postDelayed(r, 60*1000);
   }
Kailash Ahirwar
  • 771
  • 3
  • 14
  • To solve the posted requirement with this approach, you'd have to use your runnable to turn off a flag that was blocking the shouldn't-happen-too-often task. – Chris Stratton Sep 20 '13 at 18:56
0

If your main goal is just to avoid "Toast Spamming", this can be avoided quite easily. Please see my solution to Best way to avoid Toast accumulation in Android. It also contains a complete code sample.

Community
  • 1
  • 1
Ridcully
  • 23,362
  • 7
  • 71
  • 86