定期从java程序调用Restful api

时间:2014-05-20 09:52:27

标签: java http

您好我正在开发一个java应用程序,我需要在特定时间间隔(比如10秒)后一次又一次地调用Restful api,这将持续几天。 (我正在使用Apache HttpClient库来调用该服务。)

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

实现这一目标的最有效方法是什么?

2 个答案:

答案 0 :(得分:1)

可以使用调度程序或计时器来经常进行呼叫。您也可以将该代码放在while循环中并检查System.currentTimeMillis(),对其运行模数运算以返回时间并放入代码

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
    }
}

答案 1 :(得分:0)

看看Quartz Scheduler。对于restful api,我认为Jersey framework比Apache HttpClient更容易使用。