A better way to run code for a period of time

前端 未结 4 651
遥遥无期
遥遥无期 2020-12-13 22:50

I need to run some code for a predefined length of time, when the time is up it needs to stop. Currently I am using a TimerTask to allow the code to execute for a set amount

4条回答
  •  佛祖请我去吃肉
    2020-12-13 23:10

    It should also be noted that generally you only need to create one Timer(). From the code snippet I would guess you are creating multiple Timer() objects.

    The time in the schedule method is the time to run at, not how long to run for.

    Consider putting a start time before the for loop & putting a break in the for loop if you have exceeded the time limit.

    long startedAt = System.currentTimeMillis();
    long finishedCorrectly = true;
    for (int j = 0; j < Coords.size(); j++) {
      newCoOrds += Coords.get(j) + " ";
      if ((System.currentTimeMillis() - startedAt) > MAX_TIME_TO_RUN) {
        finishedCorrectly = false;
        break;
      }
    }
    

提交回复
热议问题