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

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

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!

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. new Thread() {
  6. public void run() {
  7. Document doc;
  8. try {
  9. doc = Jsoup.connect(&quot;http://google.comt/&quot;).get();
  10. runOnUiThread( new Runnable()
  11. {
  12. public void run()
  13. {
  14. // do stuff
  15. }
  16. });
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. if (System.nanoTime() &lt;= 10000000000L) { // 10 seconds
  20. run(); // RECURSIVE CALL
  21. }
  22. }
  23. }
  24. }.start
  25. }

答案1

得分: 1

以下是已翻译的内容:

  1. long startTime = System.currentTimeMillis();
  2. while (System.currentTimeMillis() - startTime <= 10000) {
  3. run();
  4. }

如果您想使用纳秒,您可以尝试如下:

  1. long startTime = System.nanoTime();
  2. while (System.nanoTime() - startTime <= 10000000000) {
  3. run();
  4. }
英文:
  1. long startTime = System.currentTimeMillis();
  2. while(System.currentTimeMillis() - startTime &lt;= 10000){
  3. run();
  4. }

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

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

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:

确定