The process of listening to files on tomcat

I need a very simple process that listens to a directory and performs some operation when a new file is created in that directory.

I think I need a thread pool that does this.

It is very simple to implement using the spring framework, which I usually use, but I cannot use it now. I can only use tomcat, how can I implement it? What is the entry point that "launches" this thread?

Should there be a servlet?

thanks

+4
source share
3 answers

since you clarified the question, here is another answer: how to start the daemon in tomcat:

first register your daemons in web.xml:

<listener> my.package.servlet.Daemons </ listener>

then implement the Daemons class as an implementation of ServletContextListener as follows:

the code will be called every 5 seconds, tomcat will call contextDestroyed when your application shuts down. note that the variable is volatile, otherwise problems may occur when turning off multi-core systems.

 import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class Daemons implements ServletContextListener { private volatile boolean active = true; Runnable myDeamon = new Runnable() { public void run() { while (active) { try { System.out.println("checking changed files..."); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; public void contextInitialized(ServletContextEvent servletContextEvent) { new Thread(myDeamon).start(); } public void contextDestroyed(ServletContextEvent servletContextEvent) { active = false; } } 
+4
source

You can create a listener to start the stream, however this is not a good idea. When you work inside a web container, you should not start your own threads. There are several questions in Qaru why this is so. You can use Quartz (the scheduler structure), but I think you could not achieve an acceptable resolution.

In any case, what you are describing is not a web application, but rather a daemon service. You can implement this regardless of your web application and create a means for them to communicate with each other.

+1
source

In java 7 a true java file notifiaction will be added. Here is the part of javadoc that describes it roughly .

An implementation that monitors events from the file system is intended to directly map to the event notification tool on the native file, where available

right now you’ll either have to create your own platform-dependent program that does this for you,

or, alternatively, implement some kind of survey that so often registers a directory to detect changes.

there is a notification library that you can use right now - it uses the C program in linux to detect changes in sourceforge. on windows he uses polling. I did not try to check if it works.

+1
source

All Articles