10秒后执行语句

时间:2014-05-30 09:14:21

标签: java timer

我正在运行我的java侦听器代码。

我的服务器会向客户端发送一些命令。

此后我想在10s内等待,如果没有回复,则继续重试5次。

以下是我的工作。

//Select code from the db with the codeID, codeText.
//send the code to the client.
long t= System.currentTimeMillis();
long end = t+10000;
while(System.currentTimeMillis() < end) {

}
//Select from db to check if codeupdated.

如果更新不做任何其他事情,我需要重复上述暂停?

我有问题要重复5次吗?

3 个答案:

答案 0 :(得分:1)

使用

Thread.sleep(10*1000); //sleep 10 seconds.

答案 1 :(得分:1)

无法保证您的构造完全持续10秒,并且在性能方面成本非常高。

只需使用Thread.sleep即可。

for (int i = 0; i < 5; i++) {
        // TODO your request here
        boolean success = true; // TODO change to whatever outcome of your
                                // request
        if (success) {
            break;
        }
        else {
            try {
                Thread.sleep(10000l);
            }
            catch (InterruptedException ie) {
                // TODO handle interruptions if applicable
            }
        }
    }

答案 2 :(得分:1)

您应该使用Thread.sleep()暂停执行

这里解释得很好: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

相关问题