开发者

Run task for defined time

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 CountdownT开发者_JAVA技巧imer but without ticks. I only want define a start and endtime and my task should perform in this period.


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜