A better way to run code for a period of time

前端 未结 4 633
遥遥无期
遥遥无期 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条回答
  •  -上瘾入骨i
    2020-12-13 23:08

    [...] Currently I am using a TimerTask to allow the code to execute for a set amount of time [...]

    The timer task will never stop the currently running task. In fact, it's only purpose is to restart the task over and over again.

    There is no easy way of solving this without tight cooperation with the executing task. The best way is to let the task monitor it's own execution, and make sure that it returns (terminates) when its time is up.

提交回复
热议问题