英文:
How to recursively call a function for a set period of time?
问题
我会翻译您提供的内容,不包括代码部分。以下是翻译好的部分:
我想在捕获到我的 IOException 时递归调用 run() 函数,但前提是该方法的总执行时间必须 <= 10 秒。我故意拼写错误了 google.com 链接,以便始终抛出并捕获 IOException,但似乎 run() 方法并没有成功递归调用。我在这里做错了什么?任何帮助将不胜感激,谢谢!
英文:
I would like to recursively call the run() function when my IOException is caught if and only if the total execution time for this method has been <= 10 seconds. I mistyped the google.com link purposely so that the IOException always gets thrown and caught but it seems like the run(); method isn't being successfully recursively called. What did I do wrong here? Any help would be appreciated, thanks!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
public void run() {
Document doc;
try {
doc = Jsoup.connect("http://google.comt/").get();
runOnUiThread( new Runnable()
{
public void run()
{
// do stuff
}
});
} catch (IOException e) {
e.printStackTrace();
if (System.nanoTime() <= 10000000000L) { // 10 seconds
run(); // RECURSIVE CALL
}
}
}
}.start
}
答案1
得分: 1
以下是已翻译的内容:
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime <= 10000) {
run();
}
如果您想使用纳秒,您可以尝试如下:
long startTime = System.nanoTime();
while (System.nanoTime() - startTime <= 10000000000) {
run();
}
英文:
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime <= 10000){
run();
}
If you want use nano seconds, you can try as below:
long startTime = System.nanoTime();
while(System.nanoTime() - startTime <= 10000000000){
run();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论