Run task for defined time

时间秒杀一切 提交于 2019-12-10 11:45:59

问题


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:


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


来源:https://stackoverflow.com/questions/4906433/run-task-for-defined-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!