简体   繁体   English

如何为特定的小时和分钟制作 Timer.schedule()?

[英]how to make a Timer.schedule() for specific hours and minutes?

i tried to make the schedule() method wait till a specific hour and minute comes and start to execute the task but it didnt work because the method schedule() doesnt take hours and minutes as an argument, what is the replacment for this method?我试图让schedule()方法等到特定的小时和分钟到来并开始执行任务,但它没有工作,因为方法schedule()不需要小时和分钟作为参数,这个方法的替换是什么? i'm i supposed make schedule for hours then when the hour comes the program check the minutes?我应该安排几个小时的时间表,然后当小时到来时,程序检查分钟? then if both are correct it will start executing or what?那么如果两者都正确,它将开始执行还是什么?

PS for making things easier to understand, how to make something similier to this: PS为了让事情更容易理解,如何制作与此类似的东西:

schedule(new TimerClass(), desired hours , desired minutes )?时间表(新 TimerClass(),所需的小时数所需的分钟数)?

You don't need to such a hardcoding.Testing hour then minutes.Just schedule the task like below.你不需要这样的硬编码。测试小时然后分钟。只需安排如下任务。 The task given below will execute after one hour and will be repeated in each 30000ms.If you need execution only once then cancel the time after first execution like using t.cancel() and also convert Hour+minute to ms to put the scheduled time下面给出的任务将在一小时后执行,并且每 30000 毫秒重复一次。如果您只需要执行一次,则在第一次执行后取消时间,如使用 t.cancel() 并将 Hour+minute 转换为 ms 以放置预定时间

 TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();


scanTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                         //do your task here    

                    }
               });
        }};

t.schedule(scanTask, 1*60*60*1000, 30000); 

If you want to schedule for a particular clock time (rather than a delay from current time), here are some options:如果您想安排特定的时钟时间(而不是从当前时间延迟),这里有一些选项:

  • Use Quartz , if you're doing this enough to justify the additional library.如果您这样做足以证明附加库的合理性,请使用Quartz Quartz makes it easy to specify clock times, and supports scheduling recurring events. Quartz 可以很容易地指定时钟时间,并支持调度重复事件。
  • Otherwise, at the time you're scheduling, compute the difference between the current time and the desired time.否则,在您计划时,计算当前时间和所需时间之间的差异。 (Use the Calendar class to create clock times, convert to Dates, and getMillis().) Feed the difference to Timer -- or ScheduledThreadPoolExecutor. (使用日历 class 创建时钟时间,转换为日期,然后 getMillis()。)将差异提供给 Timer -- 或 ScheduledThreadPoolExecutor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM