在使用postDelayed特定时间运行的任务

编程入门 行业动态 更新时间:2024-10-09 15:24:17
本文介绍了在使用postDelayed特定时间运行的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在特定的时间来启动一个任务。对于我使用可运行和 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特定时间运行的任务

本文发布于:2023-11-27 14:25:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   postDelayed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!