How to run Java services (or background daemon processes) in an application server or web container?


I’ve presented here a simple example to illustrate how to convert stand-alone java programs (mostly, JARs) to WARs which can then be deployed in full-blown application servers (JBoss, WebSphere, etc.) or light weight web containers (Tomcat, Jetty, etc.). This’s generally done to avoid the hassle of managing background daemon processes separately. Also, deploying all of these apps together in an application server gives a layer of additional stability, and makes it easily controllable.

Here’s the code, and I’ll add comments when I get some time:

package sample.archetype.webapp.daemon;

public class DaemonMain {

    static PrintTask printTask = null;

    public static void main(String[] args) {

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
        {
            public void run()
            {
                // Do cleanup operations here
                printTask = null;
                System.out.println("Cleanup activity: PrintTask instance set to null");
            }
        }));

        // Invoke the daemon/background process code
        printTask = new PrintTask("Hello World!");
        printTask.invokeIndefinitePrintTask();
    }

}
package sample.archetype.webapp.daemon;

public class PrintTask {

    String message;

    public PrintTask(String message){
        this.message = message;
    }

    private void printMessage(){
        System.out.println("Message: " + message);
    }

    public void invokeIndefinitePrintTask(){
        while(true){
            printMessage();

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("Caught an exception while sleeping.
                     Description: " + e.getMessage());
            }
        }
    }

}
package sample.archetype.webapp.daemon;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AppStartUp implements ServletContextListener{

    PrintTask printTask = null;

    public void contextDestroyed(ServletContextEvent arg0) {
        // Do cleanup operations here
        printTask = null;
        System.out.println("Cleanup activity: PrintTask instance set to null");
    }

    public void contextInitialized(ServletContextEvent arg0) {
        // Invoke the daemon/background process code
        printTask = new PrintTask("Hello World!");
        printTask.invokeIndefinitePrintTask();
    }

}
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Archetype Created Web Application</display-name>

    <listener>
        <listener-class>sample.archetype.webapp.daemon.AppStartUp</listener-class>
    </listener>

</web-app>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>sample.archetype.webapp.daemon</groupId>
    <artifactId>webapp_daemon</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    webapp_daemon Maven Webapp
    <url>http://maven.apache.org</url>
    <dependencies>

        <dependency>
            <groupId>javax.servlet</groupId>
            servlet-api
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>webapp_daemon</finalName>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <version>1.1</version>
                <configuration>
                    <port>9999</port>
                    <path>/webapp</path>
                    <warFile>${project.basedir}/target/${project.build.finalName}.war</warFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
About these ads

7 comments

  1. Interesting article. I guess if you need to run a thread inside your application on a web server that is one way to do it. However, items that need to be run on some sort of configurable periodicity should probably use Quartz Scheduler, or the EE5/EE6 Timer mechanism.

  2. yeah, you’re right. For those scenarios, I’ve used Spring framework. It has inherent support for task scheduling, and if there’s a requirement to use Quartz too, it provides me with helper classes to configure it without much fuss.

    ~Sing

  3. Tiago Espinha · · Reply

    This is pretty cool, exactly what I was looking for :) I was also having troubles finding it on Google because I didn’t know what exactly to search for.

    Anyway, great post!

  4. Tejendra Pratap Singh · · Reply

    thats nice exactly what i looking for!!!!! thanks for the effort.

  5. thanks a lot it’s exactly what I’m looking for bout 1 month

  6. Thanks for the sample!

  7. Thanks for this example. I tried implementing it to my app and encountered a weird problem: The Managed server it is deployed to goes into the state STARTING and never gets to RUNNING. Might have to do with the deamon running endlessly? Do you perhaps know how to avoid this?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 27 other followers

%d bloggers like this: