Reputation: 28555
How can I execute some code, once a day. e.g. call MyMethod() at 3pm every day. (provided the app is running of course)...
Im trying to do this in c# winforms.
Upvotes: 0
Views: 9068
Reputation: 41
I see this question is quite old but I reached it for the need expressed in the subject. I ended up with a simpler code using just DateTime class. I tested it and it's working just fine, here's the code:
DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, min), 0);
while (!stoppingToken.IsCancellationRequested)
{
if (DateTime.Now > start)
{
start = start.AddDays(1);
....do_your_stuff.....
}
await Task.Delay(1000, stoppingToken);
}
I hope it can be useful.
Upvotes: 0
Reputation: 499352
If you simply want to run something at the same time every day, you can use the built in task scheduler.
You can setup a daily schedule that will execute your application at the same time every day.
Otherwise, in your application you will need to setup a timer and check in the tick event if the current time is 3pm and only call your method at that point.
I would have suggested a windows service, but as you stated that you only need the method to run if the application is already running, this is not needed.
Upvotes: 2
Reputation: 3785
The task scheduler is the best option. If you need to do it inside a .NET application there is no component that allows you to trigger an event at a specific time. But you can set up a Timer to raise an event every minute (for example, but you can set up a smaller o bigger interval depending on your needs), then in the handler you check the current time and if it is 3pm you can execute your code, else do nothing.
Upvotes: 4
Reputation: 1100
Or if you want more control you can create a Windows Service. Simply inherit from System.ServiceProcess.ServiceBase and add a timer on the OnStart override. Install your windows service on the machine.
Upvotes: 2
Reputation: 10753
Windows Service and a Timer!
check out codeproject's simple windows server:
http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
Upvotes: 2