Question

I need a very simple process that listens on a directory and does some operation when a new file is created on that directory.

I guess I need a thread pool that does that.

This is very easy to implement using the spring framework, which I normally use but I can't use it now. I can only use tomcat, How can I implement it? what is the entry point that "starts" that thread?

Does it have to be a servlet ?

thanks

Was it helpful?

Solution

since you refined the question, here comes another answer: how to start a 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 like this:

the code will be called every 5 seconds, tomcat will call contextDestroyed when your app shuts down. note that the variable is volatile, otherwise you may have troubles on shutdown on 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;
}
}

OTHER TIPS

You could create a listener to start the thread, however this isn't a good idea. When you are running inside a Web container, you shouldn't start your own threads. There are a couple of questions in Stack Overflow for why is this so. You could use Quartz (a scheduler framework), but I guess you couldn't achieve an acceptable resolution.

Anyway, what you are describing isn't a Web application, but rather a daemon service. You could implement this independently from your web application and create a means for them to communicate with each other.

true java-only file notifiaction will be added in java 7. here is a part of the javadoc that describes it roughly.

The implementation that observes events from the file system is intended to map directly on to the native file event notification facility where available

right now you will have to either create a native platform-dependent program that does that for you,

or alternatively implement some kind of polling, which lists the directory every so often to detect changes.

there is a notification library that you can use right now - it uses a C program on linux to detect changes over at sourceforge. on windows it uses polling. i did not try it out to see if it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top