我想在特定的时间来启动一个任务。对于我使用可运行和 postDelayed 方法如下:
I would like to start a task at a specific time. For that I use runnable and postDelayed method as follows:
private Runnable mLaunchTask = new Runnable() { public void run() { try { MY TASK } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } };在我的code我用 mLunchTask 如下:
In my code I use mLunchTask as follows:
mHandler = new Handler(); mHandler.postDelayed(mLaunchTask, myDelay*1000);和 myDelay 的计算方法如下:
s = DateFormat.format("hh:mm:ss aaa", d.getTime()); cTime = s.toString(); // current Time ch = Integer.parseInt(cTime.substring(0,2)); // current hour cm = Integer.parseInt(cTime.substring(3,5)); // current minute cs = Integer.parseInt(cTime.substring(6,8)); // current second if (cTime.substring(9,11).equalsIgnoreCase("pm") && (ch<12) ) ch = ch+12; myDelay=(desiredHour-ch)*3600+(desiredMinute-cm)*60 - cs; if (myDelay<0) myDelay = 0;和 desiredHour 和 desiredMinute 是由用户设置。人们期望的是,我的任务开始于 desiredHour 和 desiredMinute 和0秒。但是我的任务开始以几秒钟的延迟,这看起来就像是随机的。
and desiredHour and desiredMinute are set by user. The expectation is that MY TASK starts at desiredHour and desiredMinute and 0 seconds. However "MY TASK starts with a few seconds delay, which looks like is random.
,没有任何理由,它并没有在精确的期望的时间开始的?
Based on the above code, is there any reason that it does not start at the exact desired time?
感谢
推荐答案首先,你的延迟计算是正确的,但点检测不与其他语言。最好就是用日历来获得延迟:
First of all, your delay calculation is correct, but the "pm" detection doesn't work with other languages. It is much better to use the calendar to get the delay:
Calendar calendar = Calendar.getInstance(); long currentTimestamp = calendar.getTimeInMillis(); calendar.set(Calendar.HOUR_OF_DAY, desiredHour); calendar.set(Calendar.MINUTE, desiredMinute); calendar.set(Calendar.SECOND, 0); long diffTimestamp = calendar.getTimeInMillis() - currentTimestamp; long myDelay = (diffTimestamp < 0 ? 0 : diffTimestamp);现在你在毫秒的延迟,并可以开始处理程序:
Now you have the delay in milli secs and can start the handler:
new Handler().postDelayed(mLaunchTask, myDelay);在我的测试下在没有延迟所需的时间可运行的日志。
In my test the following runnable logs at the desired time with no delay.
private Runnable mLaunchTask = new Runnable() { public void run() { Calendar calendar = Calendar.getInstance(); Log.d("test", "started at " + calendar.get(Calendar.HOUR_OF_DAY) + " " + calendar.get(Calendar.MINUTE) + " " + calendar.get(Calendar.SECOND) ); } };也许你开始任务需要几秒钟加载?
Maybe your started task needs some seconds to be loaded?
请问 AlarmManager 是一种选择?
更多推荐
在使用postDelayed特定时间运行的任务
发布评论