仅当超过 5 秒时,才能再次调用方法

我有一个应用程序正在运行,我有点想创建一个超时,我的方法在很短的时间内被调用了太多次。我想确定只有在通过5秒时才能再次调用该方法。我该怎么做?


炎炎设计
浏览 82回答 2
2回答

慕的地10843

无需进入线程和计时器等的简单方法是在调用方法时获取当前时间并存储它。在下一次呼叫中,您将新的当前时间与旧时间进行比较。如果 5 秒未过去,则不执行任何操作。例如:long lastCall = 0;void doSomething(){    long now = secondsSinceEpoch();    if (lastCall == 0 || now-lastCall > 5)    {        // Do stuff        // lastCall = now    }}

牛魔王的故事

我不知道这是否能帮助你。private long timeMillions = 0;&nbsp; &nbsp; public void doSomething(){&nbsp; &nbsp; &nbsp; &nbsp; // if within 5 seconds&nbsp; &nbsp; &nbsp; &nbsp; if(System.currentTimeMillis() < timeMillions + 5 * 1000){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //retrun or do some thing else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // after 5 seconds&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeMillions = System.currentTimeMillis();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("do something");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java