Java中的一些延迟后的调用方法 [英] Call method after some delay in java
问题描述
场景就像:
在我的应用程序中,我打开了一个文件,对其进行了更新并保存.一旦文件保存事件被触发,它将执行一种方法abc()
.
但是现在,我想在保存事件触发后添加延迟,例如1分钟.因此,我添加了Thread.sleep(60000)
.现在,它在1分钟后执行方法abc()
.到现在一切正常.
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.
但是假设用户在1分钟内保存了3次文件,则该方法在每1分钟后执行3次.我只想在第一次保存后的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.
我该如何处理这种情况?
How can I handle such scenario?
推荐答案
在YourClassType
让我们说: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
}
这篇关于Java中的一些延迟后的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!