0

Hi I'm developing a java application wherein I need to call Restful api again and again after a specific time interval (say 10 seconds) and this would continue for a few days. (I'm using Apache HttpClient library to call the service.)

HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(rest-URL);
HttpResponse response = client.execute(getRequest);

Which is the most efficient way to achieve this?

Archit Arora
  • 2,508
  • 7
  • 43
  • 69
  • Use scheduler or call the rest url using unix/shell scripts – ukanth May 20 '14 at 09:54
  • 1
    Add the request to a [Scheduled Executor Service](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html). – christopher May 20 '14 at 09:55

2 Answers2

1

Schedulers or Timers could be used to make the call every so often. You could also put that code inside a while loop and check System.currentTimeMillis(), run a modulus operation on it to return the time and drop into your code

Working from this answer.

while(true){
    long milliseconds = System.currentTimeMillis();
    int seconds = (int) (milliseconds / 1000) % 60 ;
    int minutes = (int) ((milliseconds / (1000*60)) % 60);
    int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

    if( /* time is right */ ){
         //  REST calls here
    }
}
Community
  • 1
  • 1
Kyte
  • 834
  • 2
  • 12
  • 27
  • This is a form of pooling. Won't this consume a lot of unnecessary CPU time? A java scheduler like Quartz or cron4j can be used instead. – Swapnil B. Jun 09 '18 at 19:33
0

Take a look at Quartz Scheduler. For the restful api, I think Jersey framework is much easier to use than Apache HttpClient.

pmichna
  • 4,800
  • 13
  • 53
  • 90