Call method after some delay in java

旧街凉风 提交于 2019-12-05 18:02:29

问题


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.

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?


回答1:


Use Timer and TimerTask

create a member variable of type Timer in YourClassType

lets say: 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
}



回答2:


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?

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?



来源:https://stackoverflow.com/questions/18612656/call-method-after-some-delay-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!