Run task for defined time

2019-06-03 06:48发布

Is there in Android an efficent way to run a task only for a limited time? Currently I use a Handler with onPostDelayed() and check each run if the current timestamp is higher than my predefined timestamp.

I'm searching for a solution like CountdownTimer but without ticks. I only want define a start and endtime and my task should perform in this period.

1条回答
等我变得足够好
2楼-- · 2019-06-03 07:05

If I want to run a task for a specific time I save the time it starts into a 'long' like so:

long now = System.currentTimeMillis();

And then simply check how long it has been since the task started (assuming it is a loop of some kind) while it is running so if I wanted to run something for 5 seconds:

long now = System.currentTimeMillis();
int runtime=5000;//in milliseconds
do
{
    //enter your code here
}while (now+runtime<System.currentTimeMillis());
查看更多
登录 后发表回答