'Is there a way to block a method running if it has been a short period of time after it was last run?

I have a method that I only want to run if it hasn't been ran in the last n milliseconds.

For example:

public boolean tooLong(int n) {
    int timeSince = timeSinceLastExecution(tooLong);
    //Returns an integer of how long it has been since the last time the tooLong method has been executed
    
    if (timeSince > n)
        return true;
    return false;
}

Is there anything that can replace timeSinceLastExecutionMethod that can return a similar result?



Solution 1:[1]

There is no built-in function for this, both because it’s uncommon, and because it’s easy to implement oneself:

private static final long MIN_COOLDOWN = Duration.ofMinutes(5).toMillis();

private long lastCallTime;

public boolean tooLong(int n) {
    long now = System.currentTimeMillis();
    if (now - lastCallTime < MIN_COOLDOWN) {
        return false;
    }

    lastCallTime = now;

    // Actual method logic goes here.

    return true;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VGR