在java中延迟一段时间后调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18612656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:31:11  来源:igfitidea点击:

Call method after some delay in java

javamultithreadingdelay

提问by Naresh J

Scenario is like :

场景是这样的:

In my application, I opened one file, updated it and saved. Once the file saved event get fired and it will execute one method abc(). But now, I want to add delay after save event get fired, say 1 minute. So I have added Thread.sleep(60000). Now it execute the method abc()after 1 minute. Till now all works fine.

在我的应用程序中,我打开了一个文件,更新并保存了它。一旦文件保存事件被触发,它将执行一种方法abc()。但是现在,我想在保存事件被触发后添加延迟,比如 1 分钟。所以我添加了Thread.sleep(60000). 现在它abc()在 1 分钟后执行该方法。直到现在一切正常。

But suppose user saved file 3 times within 1 minute, the method get executed 3 times after each 1 minute. I want to execute method only one time in next 1 minute after first save called with latest file content.

但是假设用户在 1 分钟内保存了 3 次文件,则该方法每 1 分钟执行 3 次。在第一次使用最新文件内容调用的保存后,我想在接下来的 1 分钟内只执行一次方法。

How can I handle such scenario?

我该如何处理这种情况?

采纳答案by Philipp Sander

Use Timerand TimerTask

使用TimerTimerTask

create a member variable of type Timerin YourClassType

创建一个类型为Timerin的成员变量YourClassType

lets say: private Timer timer = new Timer();

让我们说: private Timer timer = new Timer();

and your method will look something like this:

你的方法看起来像这样:

public synchronized void abcCaller() {
    this.timer.cancel(); //this will cancel the current task. if there is no active task, nothing happens
    this.timer = new Timer();

    TimerTask action = new TimerTask() {
        public void run() {
            YourClassType.abc(); //as you said in the comments: abc is a static method
        }

    };

    this.timer.schedule(action, 60000); //this starts the task
}

回答by Calin Burley

If you are using Thread.sleep(), just have the static method change a static global variable to something that you can use to indicate blocking the method call?

如果您使用 Thread.sleep(),只需让静态方法将静态全局变量更改为可用于指示阻塞方法调用的内容?

public static boolean abcRunning;
public static void abc()
{
    if (YourClass.abcRunning == null || !YourClass.abcRunning)
    {
        YourClass.abcRunning = true;
        Thread.Sleep(60000);
        // TODO Your Stuff
        YourClass.abcRunning = false;
    }
}

Is there any reason this wouldn't work?

有什么理由这不起作用吗?