Run System.Timers.Timer event on specific day and

2019-08-11 06:27发布

问题:

This question already has an answer here:

  • How to call a method daily, at specific time, in C#? 14 answers

I'm in the process of writing a windows service using System.Timers.Timer to keep track of my interval. What I'd like to do is make it so my service will launch on a specific day and time based on variables in my app.config file.

回答1:

I don't think you're really writing a Windows service, I think you're writing a job. A cleaner, and easier approach, to your problem would be to write a Console application and then setup a Windows Scheduled Task to run that Console application at the intervals you want.

Never mind the fact that you'll have to set the time in milliseconds with the Timer approach, the Windows service would not be capable of handling Daylight Savings Time and more.



回答2:

Although I think your best bet is to make this a scheduled task, you can easily create a waitable timer that will signal at the same time every day. Windows has a Waitable Timer object, but there's no .NET support for it.

I published an article a while back called Waitable Timers in C#, in which I showed how to use this object from a C# program. Unfortunately, the site that published the article is no longer. However, you can download the code examples for the article from my site at http://www.mischel.com/pubs/waitabletimer.zip. You're free to use the code in any way you see fit.



标签: c# .net timer