[英]How to stop execution after certain time in java
我正在嘗試向 java 中的步驟添加重試邏輯。 使用計時器,我可以在一定時間后重復此步驟。 但是,如果該步驟未成功執行,則計時器會一直等到執行停止。 我的要求是我需要在 30 秒后停止執行此步驟,然后重試此邏輯。
以下是我正在嘗試做的事情。
步驟說明:我將通過提供 Json 輸入來調用方法 processRequest。 此步驟每次都會成功執行並返回一個作業 ID。 我正在輪詢 url 以獲取對提供的作業 ID 的響應。 此步驟有時無法成功執行或需要大量時間才能返回響應。 我想終止這個輪詢任務並重試再次調用 processRequest,這會生成一個新的作業 ID,並且必須將其發送以進行輪詢。 該邏輯必須在等待 30 秒后執行 5 次。
Json request={operation:resize};
String JOBID=processRequest(request);
String response=http://pollingUrl/JOBID;
我可以在不將我的 class 擴展到線程 class 的情況下做到這一點,或者請建議是否還有其他方法可以實現相同的目標。
我正在尋找這樣的東西:
String response="";
Int count=5;
While (count>0)
{
String JOBID=processRequest(request);
String response=http://pollingUrl/JOBID; // terminate step after 30s
If response !="";
Return response; // return response and stop the while loop.
}
一種可能的方法是使用Thread.sleep()
。 假設您不介意將程序鎖定 30 秒,您可以執行以下操作:
String response="";
int count=5;
While (count>0) {
String JOBID=processRequest(request);
String response=http://pollingUrl/JOBID;
if (!response.equals("")) {
return response; // return response and stop the while loop.
}
try {
Thread.sleep(6000); // 6 seconds
} catch (InterruptedException ie) {}
count--;
}
請注意,除非 http 輪詢調用是非阻塞的,否則上述方法將不起作用。 也就是說,如果它在內部等待直到提供響應,它將無法工作。 但通常當輪詢調用完成時,應該有一種機制在某個時候超時。
編輯:我改變了兩件事。 我在測試后移動了睡眠以獲得響應。 我修改了你測試平等的方式(這可能是問題的一部分)。 使用equals
而不是==
或!=
來比較字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.