如何在一段固定时间内递归调用一个函数?

huangapple go评论81阅读模式
英文:

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(&quot;http://google.comt/&quot;).get();
          
            runOnUiThread( new Runnable()
            {
                public void run()
                {
                     // do stuff
                }
            });

        } catch (IOException e) {                          
            e.printStackTrace(); 
            if (System.nanoTime() &lt;= 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 &lt;= 10000){
  run();
}

If you want use nano seconds, you can try as below:

long startTime = System.nanoTime();
    while(System.nanoTime() - startTime &lt;= 10000000000){
      run();
    }

huangapple
  • 本文由 发表于 2020年8月5日 13:21:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63258855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定