Question

I want to start a service which starts along with Server and never ends until server is killed. So first I have gone with ServletContextListner class where I implemented my logical part to run the method using

while(true){ 
    try{ // do the jobs } 
    catch(Exception e){} 
}

But then i felt it's not good to implement this job at Listener class. Then I moved to one ServiceManager class and doing the same job, but gives me an edge in injecting properties using Spring which is not possible in Listener class.

But fundamental question on how better/from where can I invoke this class and call the startService method which runs infinitly.

public void contextInitialized(ServletContextEvent event) {
        logger.info(" *** START MyListener ****");
        context = event.getServletContext();
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
        MyServiceManager serviceManager = (MyServiceManager) ctx.getBean("myServiceManager");
        serviceManager.startService();
        logger.info(" *** END MyListener ****");
    }

or any idea how to invoke/implement such service to run in server forever without any abstractions [under any case, this shouldn't be killed unless server is stopped]

Was it helpful?

Solution

This is a duplicate question see: Background process in Servlet

So you can do what is explained in that answer and if you need to then load your Spring configured beans using applicationContext.getBean("yourBean");

OTHER TIPS

Are you open to alternate technologies, namely Node.js ?

I am not sure what your server does, however I had to build a "always-on" Push notification server for iOS and I used Node.js to do that.

If yes, you can build your system like this:

Building the system

1) You setup a web service using your Java to return JSON data to your Node.js server when your Java server receives a HTTP web request (POST request)

2) Your Node.js makes the POST request to your Java server, gets the results and parses it and sends it to your other systems

Always-On Server with fault tolerance

With Node.js installed, you can use Node.js's NPM (Node.js Package Manager) to install the Forever tool.

Then using Forever tool, you can go:

forever start server.js

to start the infinite process with automatic fault tolerance, you can also list the daemon jobs currently managed by forever tool:

forever list

Note: you do not need to use infinite while loops with Node.js, when you start a Node.js http server, it will keep running until you tell it to stop.

When your server starts up, restarts, loses power or whatever, Forever will automagically spawn a new process, giving your automatic fault tolerance.

Hope that helps.

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