Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way of firing an event at a particular time of day?

Tags:

c#

events

I have an app that needs to fire off a couple of events at certain times during the day - the times are all defined by the users. I can think of a couple of ways of doing it but none of them sit too well. The timing doesn't have to be of a particularly high resolution - a minute or so each way is fine.

My ideas :

  1. When the app starts up read all the times and start timers off that will Tick at the appropriate time

  2. Start a timer off that'll check every minute or so for 'current events'

tia for any better solutions.

like image 254
PaulB Avatar asked Apr 07 '09 14:04

PaulB


2 Answers

  • Store/index the events sorted by when they next need attention. This could be in memory or not according to how many there are, how often you make changes, etc. If all of your events fire once a day, this list is basically a circular buffer which only changes when users change their events.
  • Start a timer which will 'tick' at the time of the event at the head of the list. Round up to the next minute if you like.
  • When the timer fires, process all events which are now in the past [edit - and which haven't already been processed], re-insert them into the list if necessary (i.e. if you don't have the "circular buffer" optimisation), and set a new timer.

Obviously, when you change the set of events, or change the time for an existing event, then you may need to reset the timer to make it fire earlier. There's usually no point resetting it to fire later - you may as well just let it go off and do nothing. And if you put an upper limit of one minute on how long the timer can run (or just have a 1 minute recurring timer), then you can get within 1-minute accuracy without ever resetting. This is basically your option 2.

Arguably you should use an existing framework rather than rolling your own, but I don't know C# so I have no idea what's available. I'm generally a bit wary of the idea of setting squillions of timers, because some environments don't support that (or don't support it well). Hence this scheme, which requires only one. I don't know whether C# has any problems in that respect, but this scheme can easily be arranged to use O(1) RAM if necessary, which can't be beat.

like image 116
Steve Jessop Avatar answered Oct 12 '22 02:10

Steve Jessop


Have a look at Quartz.Net. It is a scheduler framework (originally for Java).

like image 37
kgiannakakis Avatar answered Oct 12 '22 03:10

kgiannakakis