如何在一定时间后重试功能请求 [英] How to retry function request after a certain time
问题描述
如果用户数据为null,如何重试发送尝试。最多2次重试,10次后重试1次?
How do I make it retry the send attempt if user data is null. Max 2 retries, 1 retry after 10 seconds?
public class UserHandler {
private List users = new ArrayList();
public void addUser(username) {} //adds user
public Userdata findUser(username) {} //finds user
public void sendTo(String username, String message) {
Userdata user = findUser(username);
if(user != null) {
Out out = new Out(user.getClientSocket());
out.println(message);
}
}
}
我真的需要手动插入一个线程并将其放入sendTo()中?
Do I really have to manually insert a thread and sleep it inside sendTo()?
编辑:服务器使用java 1.4.2
the server uses java 1.4.2
推荐答案
首先需要解决更多的架构问题。在单线程程序中,序列通常是:
You're got more of an architectural problem to solve first. In a single-threaded program the sequence is normally:
- 做东西;
- 调用sendTo( );
- 做更多的事情。
如果你想要的话,你必须弄清楚:
You have to work out if what you want is:
- 做东西;
- 致电sendTo();
- 如果(2)失败,请等待10秒再发送给();
- 如果(3)失败,则抛出错误;
- 做更多的事情。
- Do stuff;
- Call sendTo();
- If (2) fails, wait 10 seconds and sendTo() again;
- If (3) fails, throw an error;
- Do more stuff.
重点是这仍然是同步的。如果是这样,你需要一个线程。您应该使用Java 5 Executors。
The point being that this is still synchronous. If so you'll need a thread. You should use the Java 5 Executors.
public void sendTo(final String username, final String message) {
if (!internalSendTo(username, message)) {
// attempt resend
ExecutorService exec = Executors.newSingleThreadExecutor();
final AtomicBoolean result = new AtomicBoolean(false);
exec.submit(new Runnable() {
boolean b = internalSendto(username, message);
result.set(b);
});
try {
exec.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// still didn't work
} finally {
exec.shutdownNow();
}
}
}
private boolean internalSendTo(String username, String message) {
Userdata user = findUser(username);
boolean success = false;
if (user != null) {
Out out = new Out(user.getClientSocket());
// do the communication here
success = true;
}
return success;
}
现在,这只是它如何运作的草图。然而,它应该让你对这些问题有所了解。
Now that's just a rough sketch of how it might work. It should give you some appreciation for the issues however.
你想要这个还是你想要的:
Do you want this or do you want:
- 做东西;
- 调用sendTo();
- 如果(2)失败,请对发送进行排队并继续;
- 做更多的事情。
- Do stuff;
- Call sendTo();
- If (2) fails, queue the send and keep going;
- Do more stuff.
基本上这是异步方法。如果你这样走,那么你必须回答以下问题:
Basically this is the asynchronous approach. If you go this way you then have to answer questions like:
- 如果在10秒以上(或任意间隔)之后仍然会发生什么还没有工作?
- 什么进程尝试sendTo()调用?
- 如果阻止/死亡怎么办?
- 我需要多个发件人吗?
- 等
- What happens if after 10+ seconds (or some arbitrary interval) it still hasn't worked?
- What processes attempt the sendTo() calls?
- What if they block/die?
- Do I need multiple senders?
- etc
基本上它会得到更多很复杂。
Basically it gets much more complicated.
这篇关于如何在一定时间后重试功能请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!