Within my web application, I am trying to create a directory polling bean using Java SDK7 WatchService. What I would like to achieve is to run this bean in its own thread so that it does not block the application. Something like:
<bean id="directoryPoller" class="org...MyDirectoryPoller" scope="thread"/>
I am afraid you will have to create this thread manually with Spring:
<bean id="pollThread" class="java.lang.Thread" init-method="start" destroy-method="interrupt">
<constructor-arg ref="watchServiceRunnableWrapper"/>
</bean>
<bean id="watchServiceRunnableWrapper" class="WatchServiceRunnableWrapper">
<constructor-arg ref="watchService"/>
</bean>
<bean id="WatchService" class="java.nio.file.WatchService" destroy-method="close"/>
The WatchServiceRunnableWrapper
is simple:
public class WatchServiceRunnableWrapper implements Runnable {
private WatchService WatchService;
public WatchServiceRunnableWrapper(WatchService watchService) {
this.watchService = watchService;
}
public void run() {
watchService.poll();
//
}
}
I haven't tested it, but it more-or-less should work and shutdown gracefully.
I'm not familiar with Java 7's WatchService, but you could use Springs' scheduling support for this. Here's yet another tutorial and googling for something like Spring Scheduled probably finds loads more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With