简体   繁体   English

基于Java时间的执行

[英]Java time based execution

I want to do the following. 我要执行以下操作。 I count the occurence of an event in my program. 我计算程序中事件的发生。 What I wish to achieve is that at the end of every hour (Of the MST ie the time zone where I am in) the count be recorded in the database for that hour. 我希望实现的是,在每个小时结束时(MST的时间范围,即我所在的时区),该小时数都记录在数据库中。 All I need is a code snippet which would execute at the end of every hour. 我只需要一个代码片段,该片段将在每个小时结束时执行。 Note that I don't want the thread to sleep because I also need to update counts when events occur. 请注意,我不希望线程休眠,因为当事件发生时,我还需要更新计数。

You can implement a TimerTask so search for that. 您可以实现TimerTask以便进行搜索。 Or if you can use Quartz. 或者,如果可以使用Quartz。 Google search should be your first stop. Google搜索应该是您的第一站。

In Java, there's no way to ensure that a Runnable gets executed exactly at a given time. 在Java中,无法确保Runnable在给定时间准确执行。

You can only schedule a Runnable to be executed at intervals of approximately a given time. 您只能安排一个Runnable在大约给定时间间隔执行。 If that's enough for you, then a java.util.Timer or Executors.newSingleThreadScheduledExecutor() is good enough. 如果您足够满足要求,那么一个java.util.TimerExecutors.newSingleThreadScheduledExecutor()就足够了。 You only need to put your counter in a thread-safe and atomic variable ( AtomicInteger may be enough, depending on the numbers you are expecting to have). 您只需要将计数器放在线程安全的原子变量中( AtomicInteger可能就足够了,具体取决于您期望的数字)。

If you want to have extreme precision, then you'd better modify your event handler, so that, before recording the event, it checks in which hour it is and, depending on that, it uses a different "slot" inside a queue. 如果要具有极高的精度,则最好修改事件处理程序,以便在记录事件之前,它检查在哪个小时,并根据该时间在队列中使用另一个“插槽”。 Finally, your scheduled task would gather old queue slots, removing them from the queue and storing to database. 最后,您计划的任务将收集旧队列插槽,将其从队列中删除并存储到数据库。 (I think this is excessive, but it's up to you). (我认为这太过分了,但这取决于您)。

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

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