简体   繁体   中英

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. 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. Or if you can use Quartz. Google search should be your first stop.

In Java, there's no way to ensure that a Runnable gets executed exactly at a given time.

You can only schedule a Runnable to be executed at intervals of approximately a given time. If that's enough for you, then a java.util.Timer or Executors.newSingleThreadScheduledExecutor() is good enough. 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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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