在每个请求之前添加等待时间的最佳方法是什么?
What's the best way for add a wait time before every request?
例如:
HttpClient hc =...
...
//need a wait time(Thread.sleep(xxx)) here before executing
hc.execute(post)
...
//need a wait time(Thread.sleep(xxx)) here before executing
hc.execute(get)
...
...
最好的方法是什么?非常感谢任何建议。
这取决于您是否希望至少等待一定的时间。 Thread.sleep 不保证在您作为参数提供的时间睡觉。
睡眠也可能被打断,所以你需要考虑到这一点。
你可以这样做:
public static void waitAtLeast(long millis) {
long startTime = System.nanoTime();
while (true) {
long now = System.nanoTime();
long timeWaited = (now - startTime) / 1000000L;
if (timeWaited > millis) {
return;
}
try {
Thread.sleep(millis - timeWaited);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
例如:
HttpClient hc =...
...
//need a wait time(Thread.sleep(xxx)) here before executing
hc.execute(post)
...
//need a wait time(Thread.sleep(xxx)) here before executing
hc.execute(get)
...
...
最好的方法是什么?非常感谢任何建议。
这取决于您是否希望至少等待一定的时间。 Thread.sleep 不保证在您作为参数提供的时间睡觉。 睡眠也可能被打断,所以你需要考虑到这一点。
你可以这样做:
public static void waitAtLeast(long millis) {
long startTime = System.nanoTime();
while (true) {
long now = System.nanoTime();
long timeWaited = (now - startTime) / 1000000L;
if (timeWaited > millis) {
return;
}
try {
Thread.sleep(millis - timeWaited);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}