java watchservice,Java 7 WatchService-忽略同一事件的多次出现

The javadoc for StandardWatchEventKinds.ENTRY_MODIFY says:

Directory entry modified. When a directory is registered for this

event then the WatchKey is queued when it is observed that an entry in

the directory has been modified. The event count for this event is 1

or greater.

When you edit the content of a file through an editor, it'll modify both date (or other metadata) and content. You therefore get two ENTRY_MODIFY events, but each will have a count of 1 (at least that's what I'm seeing).

I'm trying to monitor a configuration file (servers.cfg previously registered with the WatchService) that is manually updated (ie. through command line vi) with the following code:

while(true) {

watchKey = watchService.take(); // blocks

for (WatchEvent> event : watchKey.pollEvents()) {

WatchEvent watchEvent = (WatchEvent) event;

WatchEvent.Kind kind = watchEvent.kind();

System.out.println(watchEvent.context() + ", count: "+ watchEvent.count() + ", event: "+ watchEvent.kind());

// prints (loop on the while twice)

// servers.cfg, count: 1, event: ENTRY_MODIFY

// servers.cfg, count: 1, event: ENTRY_MODIFY

switch(kind.name()) {

case "ENTRY_MODIFY":

handleModify(watchEvent.context()); // reload configuration class

break;

case "ENTRY_DELETE":

handleDelete(watchEvent.context()); // do something else

break;

}

}

watchKey.reset();

}

Since you get two ENTRY_MODIFY events, the above would reload the configuration twice when only once is needed. Is there any way to ignore all but one of these, assuming there could be more than one such event?

If the WatchService API has such a utility so much the better. (I kind of don't want to check times between each event. All the handler methods in my code are synchronous.

The same thing occurs if you create (copy/paste) a file from one directory to the watched directory. How can you combine both of those into one event?

解决方案

I had a similar issue - I am using the WatchService API to keep directories in sync, but observed that in many cases, updates were being performed twice. I seem to have resolved the issue by checking the timestamp on the files - this seems to screen out the second copy operation. (At least in windows 7 - I can't be sure if it will work correctly in other operation systems)

Maybe you could use something similar? Store the timestamp from the file and reload only when the timestamp is updated?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值