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

12

场景如下:

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

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

我该如何处理这种情况?


2
使用 ScheduledExecutorService。保存从 schedule 方法返回的 future,如果以后有另一个保存操作,则取消它。 - Marko Topolnik
4
重复的问题: https://dev59.com/UXE95IYBdhLWcg3wkeof - Swapnil
3
不是真的重复。原帖作者要求增加更多功能。 - Philipp Sander
abc是一个静态方法吗? - Philipp Sander
是的,它曾经是静态的,但我将其改为非静态的。另一个人给出了答案并且它起作用了,但不幸的是他删除了他的答案。 - Naresh J
老实说:那是一个糟糕的解决方案。我会为您编辑我的答案,使其成为静态方法。 - Philipp Sander
2个回答

15

使用TimerTimerTask

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

假设:private Timer timer = new Timer();

然后你的方法会是这样的:

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
}

4
一个 Timer 实例就可以工作了;只需要取消和重新安排 tasks - Marko Topolnik

0

如果您正在使用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;
    }
}

有没有任何原因,这样不起作用?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接