2013-04-29 32 views
0

我試圖做這個事情,但沒有得到如何執行?該代碼請求網絡服務發送短信帳單信息;記帳成功或失敗時記錄網絡服務的響應。 有時需要很長時間才能得到迴應,我想取消/暫停該進程並重新發送新的數字請求。的Java暫停處理,並與其他流

long before = System.currentTimeMillis(); 
String resp = new SmsConnection().doResponseRequest(sms); 
long totalResponseTime=((System.currentTimeMillis() - before)/1000); 

我只能記錄totalResponseTime和某個需要50-100秒,得到服務的響應。有什麼辦法,我可以說

「如果resp正在超過15秒取消/暫停此請求,並在同一時間重新發送另一個。我們收到的迴應後,我們將處理該請求。」

我需要的東西就像一個超時選項用於接收響應。請建議。

感謝,

+0

你限於線程?爲什麼不使用它們,他們靈活且易於控制! – 2013-04-29 10:51:13

回答

0

你或許可以使用ExecutorService,通過提取new SmsConnection().doResponseRequest(sms);Callable。你可以看到一個例子here

+0

..謝謝。此應用程序已在ExecutorService中。如果需要太多時間才能得到迴應,我只想取消這部分。 – 2013-04-29 10:59:26

+0

感謝您的想法! – 2013-04-30 15:21:32

0

使用可贖回:

Future<String> futureResponse = service.submit(new YourCallable); //service is the ExecutorService that you use 
//this will block for 15 seconds here 
String result = futureResponse.get(15, TimeUnit.SECONDS); //this needs to wrapped in a try catch with TimeoutException 
if(result == null){ 
    //You did not get the result in 15 seconds 
    futureResponse.cancel(true);//kill this task 

    //schedule a new task 
    service.submit(new YouCallable()); 

} 
+0

@Eugene ..感謝您的想法! – 2013-04-30 15:20:57

+0

@MadanMadan http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Eugene 2013-05-01 15:59:01

0

這裏是我的問題簡單的解決方案!感謝尤金和德米特里提供的提示和建議!我創建了一個接收響應的方法,然後在同步(this){}塊中調用此方法!

public String getResponse(final StsSmsSubmit sms) throws InterruptedException, ExecutionException 
    { 
     String response=""; 
     Callable<String> responsecode=new Callable<String>() { 


     @Override 
     public String call() throws Exception { 

      final String resp = new StsSmsConnection().doRequest(sms); 
      return resp; 
     } 
    }; 
     ExecutorService service=Executors.newSingleThreadExecutor(); 
     Future task=service.submit(responsecode); 
     try{ 
     response=(String) task.get(30, TimeUnit.SECONDS); 
    } 
    catch(TimeoutException tE) 
    { 
     System.out.println("TimeOutException Occurred "+tE.getMessage()+"at "+ new Date()); 
     log.fatal("TimeOut Exception is catched. at "+ new Date()); 
     response="TimeOut"; 
    } 
     service.shutdown(); 


     return response; 

    }