如何创建一个曾经调用的Java函数,除非有一些DELAY,否则无法再次调用它?

Adi*_*pta 3 java android

我正在尝试创建一个只能在两次调用之间有一段时间延迟后再次调用的函数(比如说5秒).

我需要这个功能为我正在创建的Android应用程序.由于用户可能会在几秒钟内过于频繁地调用该功能,因此会破坏他的体验.因此,我正在拼命寻找答案.

public void doSomethin(){
//code here which makes sure that this function has not been called twice within the specified delay of 5 seconds
//Some code here
}
Run Code Online (Sandbox Code Playgroud)

任何帮助都是极好的!平硐

Jer*_*vel 13

您可以按毫秒保持时间并检查当前时间是否大于或等于前一个时间+ 5秒.如果是,则执行该方法并将当前时间替换为上一次.

请参见System.currentTimeMillis()

public class FiveSeconds {
    private static Scanner scanner = new Scanner(System.in);
    private static long lastTime = 0;

    public static void main(String[] args) {    
        String input = scanner.nextLine();

        while(!input.equalsIgnoreCase("quit")){
            if(isValidAction()){
                System.out.println(input);
                lastTime = System.currentTimeMillis();
            } else {
                System.out.println("You are not allowed to do this yet");
            }

            input = scanner.nextLine();
        }       
    }

    private static boolean isValidAction(){
        return(System.currentTimeMillis() > (lastTime + 5000));
    }
}
Run Code Online (Sandbox Code Playgroud)


Vin*_*ele 5

如果代码在主线程上运行,Thread.sleep(5000)则不是一个选项.最简单的方法是:

private long previous = 0;
public void doSomething() {
    long now = Calendar.getInstance().getTimeInMillis();
    if (now - previous < 5000)
        return;

    previous = now;
    // do something
}
Run Code Online (Sandbox Code Playgroud)