I'm trying to find a way to trigger a Silverlight event to occur at a specific time of the day. The app will be run out of browser and will be running all the time. I have found some methods that use a timer to fire an event every minute and then check if it is the correct time to do something, but that sounds messy. Is there some way of firing an event at, for example, 10:34AM on 23 September 2010?
I don't believe there is such a feature in Silverlight. If you don't like the polling approach, you could always get the difference between DateTime.Now and the target time and set a timer for that long. Though I do not know how reliable that would be.
I am not aware of any control that does what you ask for. Here are the timers that I am familiar with:
- System.Threading.Timer(interval) - Generate recurring events (Purely numeric timing without UI updates)
- System.Windows.Threading.DispatcherTimer(..) - Use in a threaded context (WPF/Silverlight)
- System.Windows.Forms.Timer() - Use windows forms message loop (WinForms in main UI thread)
I think your best bet is to use a DispatcherTimer with an interval of, say, 30 seconds, and then match the actual time with the expected time and date. From what I remember such timers are intended for small intervals, so bigger intervals will be less accurate. (I speak under correction)
EDIT: MSDN remarks on timing: "Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities."
Thanks for the responses. I still haven't found anything, but ended up using a StoryBoard as the timing component, as DispatcherTimer runs in the same thread as the UI, whereas StoryBoard doesn't.
You can read more about a comparison between the two here.
http://blogs.silverlight.net/blogs/msnow/archive/2009/11/09/69731.aspx
If you want timer to survive application restart I suggest use polling and persist scheduled tasks somewhere.
Otherwise just set timer interval to timespan between current and scheduled time.