java延迟执行方法,Java中的一些延迟后的调用方法

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?

解决方案

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值