简体   繁体   中英

Ensure method is only called once per input within x seconds

I have a method that I need to ensure runs only once within a time frame per input. For example the method would be;

void performAction(String input);

The current implementation blocks the method for x seconds for any input;

int timeOut = 0;
void performAction(String input) {
     if (hasBeenUsed()) return;
     //carryout task
}

private boolean hasCallDelay() {
   long currentTime = System.currentTimeMillis();

   if ((currentTime - timeOut) < TIME_DELAY) return true;
   timeOut = currentTime;

   return false;
}

This works for single method calls, is there an elegant way to only time out for the same input? so if "HELLO" was entered it would ignore for x time before they could call with "HELLO" again.

I was thinking maybe some kind of data structure that removes entries after some time. Also for now this will only ever be called from one thread, but I am guessing the solution above would not work with multiple threads.

This is a local service that runs, and there are a few clients that can connect to it and call the method. The problem is that the user can double press on the UI and end up calling the task twice, I can fix this on the UI however I would need to ensure that all future clients also do the same, so would rather stop it on the service.

You could try Guaua caches with Time based evictions; In a nutshell, you could configure the cache entries to get auto removed after the configured interval. Your code shall process the input if and only if it is not available in cache and before beginning the code execution, you could make sure that you add the entry into cache.

https://code.google.com/p/guava-libraries/wiki/CachesExplained

  • Use a map to note down the input vs the time of method call
  • when the input is called next time, check for the previous call time from the map.
  • If it exceeds the time frame, call the method
  • otherwise, just ignore saying any sysout statement of throwing an exception.
  • if the time frame is c=exceeded, reset the value in the map with the new call time and call the function..

have fun.. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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