2

I Have made a jax rs jersey web service. I have to load data from database when server restarts. What I am doing now is calling this url

http://localhost:8080/jersey-openshift-quickstart2/logisure/load

It loads data from database and keeps on updating it in every 20 sec by calling a thread. Based on this data other API functionalities work. Now when I deployed it on cloud I found out server restarts in every 2-3 days so I need my webservice to automatically call

http://localhost:8080/jersey-openshift-quickstart2/logisure/load

when my server restarts. How can i do it?

nitin J
  • 31
  • 2
  • 4

2 Answers2

3

You can write a ServletContextListener which calls your method from the contextInitialized() method. You attach the listener to your webapp in web.xml, e.g.

<listener>
   <listener-class>listeners.MyListener</listener-class>
</listener>

Or if you are using a Java config instead of web.xml, you do the equivalent with Java code.

And here's the code for your context listener:

package listeners;

public class MyListener implements javax.servlet.ServletContextListener {

   public void contextInitialized(ServletContext context) {
      //load data here
   }
}

This will work on whatever Servlet container and with whatever framework (you don't depend on Jersey).

Emil Gotsev
  • 223
  • 2
  • 12
2

I assume you startup a tomcat? if yes you could specify a servlet in your web.xml that you load on startup:

see this example from crunchify:

<servlet>
    <servlet-name>CrunchifyExample</servlet-name>
    <servlet-class>com.crunchify.tutorials.CrunchifyExample</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

if you use JBoss and EJBs, you could also check out either Timer EJBs - but i'm not sure if you can execute one of those right after start and only once - or the @Startup annotation or here

Using one of these possibilities you can either call your webservice from there or you could just implement whatever you implemented in your service

Community
  • 1
  • 1
tagtraeumer
  • 1,451
  • 11
  • 19