2

Have to call the servlet periodically.(like service concept in andorid)

How to do this. Using timer or any other solution?

Thanks in advance.

Amir john
  • 940
  • 1
  • 10
  • 24
  • 1
    What are you actually trying to achieve? Do something at regular intervals on the server, or actually make an HTTP request to your server periodically? – JB Nizet Oct 18 '14 at 06:05
  • Have to do something at regular intervals on the server sir. – Amir john Oct 18 '14 at 06:10
  • 2
    Then start forgetting about doing it with a servlet. A servlet's only goal is to serve HTTP requests. You don't want to deal with HTTP requests, here. All you want is to do something at regular intervals on your server. Look at http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newScheduledThreadPool%28int%29 and http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html – JB Nizet Oct 18 '14 at 06:25
  • ok sir I lookup an above links. Idea to create an class containing timer. now doubt is how to declare that class in web.xml. To declare this class in servlet(web.xml) which one is better or . – Amir john Oct 18 '14 at 06:39
  • 2
    Use a ServletContextListener. You indeed need a listener element in the web.xml or, if using a servlet 3.0+ engine, a simple WebListener annotation. – JB Nizet Oct 18 '14 at 06:48
  • @Amirjohn Basil is correct , it is better to go with experts advise – Santhosh Oct 18 '14 at 08:52

4 Answers4

4

To expand on the comments by JB Nizet…

The formerly accepted answer is kind of a hack. If the goal is to get some regular task to be performed as part of your web app, Java provides a couple of slick technologies to make this happen.

ServletContextListener

The first is a hook defined by the Servlet spec to have code invoked when a web app is deployed and when a web app is shutting down. This hook is the ServletContextListener.

ScheduledExecutorService

The second piece is the executor service added to recent versions of Java as a more sophisticated alternative to the old Timer class. In particular you need the ScheduledExecutorService.

So when your web app start up, the ServletContextListener launches a ScheduledExecutorService. When the ServletContextListener is informed of a shutdown, it tells the executor to gracefully quit.

One trick to this: Be sure to capture all exceptions in your executor. If an exception leaks, the executor silently stops executing. This is a feature not a bug. Read the doc and study up with some googling.

Search StackOverflow for examples and discussion of both of these.

Community
  • 1
  • 1
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
  • [This answer by BalusC on a duplicate question](http://stackoverflow.com/a/4691650/642706) has more detailed information. – Basil Bourque Oct 18 '14 at 17:41
1

You can use ,

response.addHeader("Refresh", "5");

"5" denotes 5 seconds .The response.addHeader("Refresh", "5") call adds a response header that is sent back to the client indicating that the browser should make another request of the servlet after 5 seconds.

Same thing can be done using html too,

<meta http-equiv="refresh" content="5" />

you can aslo pass the url here as ,

<meta http-equiv="refresh" content="5" url="example.com"/>

Also have a look at here ..

Santhosh
  • 8,045
  • 2
  • 26
  • 54
  • Thanks sir. but wat i actually want is call the method in server periodically to request or respond to client. – Amir john Oct 18 '14 at 06:14
  • Yes you can very well do that. use ajax that could refresh a part of page. check out this sample http://www.avajava.com/tutorials/lessons/how-do-i-automatically-refresh-a-servlet.html – Santhosh Oct 18 '14 at 06:18
0

If you use Java EE 6, an EJB can be packaged in the war, and you can use a @Schedule annotated EJB.

It will be executed periodically, you don't have to do anything else (run threads, or sleep).

Arjan Tijms
  • 36,666
  • 12
  • 105
  • 134
traianus
  • 101
  • 1
  • 7
-2

You can do this using Java Threads.

  1. Schedule a servlet to load on server startup. See How can I set a servlet to load on startup of the container, rather than on the first request?

  2. In this servlet's init() method, spawn a thread.

  3. In this thread's run() method, calculate the number of milliseconds to wait until the task should be performed. Then call Thread.sleep(msec). Then do the task, and loop (infinitely). The java.util.Timer class can help a lot.

Use the schedule() method of the java.util.Timer class:

long now = System.currentTimeMillis();
Date whenToRun = new Date(now+millisecondsInFuture);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
  public void run() {
// job code here
  }
};
 timer.schedule(task, whenToRun);

Or use the scheduleAtFixedRate() method of the java.util.Timer class:

int initialDelay = 30000; // start after 30 seconds
int period = 5000;        // repeat every 5 seconds
Timer timer = new Timer();
TimerTask task = new TimerTask() {
 public void run() {
// job code here
  }
};
 timer.scheduleAtFixedRate(task, initialDelay, period);
Kumar
  • 136
  • 2
  • 8
  • ok sir. Hope it helps. Is any tutorial or sample is there. – Amir john Oct 18 '14 at 06:13
  • To declare this class in servlet which one is better or . – Amir john Oct 18 '14 at 06:34
  • 1
    Never never never use `Timer` in a Java EE application! – BalusC Oct 18 '14 at 09:43
  • @BalusC sir: Why we dont want to use timer in java EE application? – Amir john Oct 18 '14 at 10:01
  • 1
    See linked duplicate. In short: it doesn't fit in the "lifetime long running" nature of a Java EE application. E.g. if an exception is thrown within a timer thread, the timer is effectively dead. It basically won't run anymore until you restart the whole server. This just doesn't make sense. – BalusC Oct 18 '14 at 10:02