Bigballs
Bigballs

Reputation: 3819

How to execute code in a C# service one time per day at the same hour

I need to start a C# service running on a server once per day at 3AM. I think that I can do it with a thread.sleep() or by comparing DateTime.Now with 3AM in code that runs 24/7.

Do you have a better solution?

Upvotes: 7

Views: 12967

Answers (6)

pavium
pavium

Reputation: 15128

I've used Scheduled Tasks successfully for backups, but I have a word of caution ...

Scheduled tasks may not be performed if you log out. I'm not sure if this can be overridden, but I have been caught out by tasks not performed because Windows automatically updates, reboots and sits waiting for me to log-in.

Another consideration is that 3AM is a time when many users would normally be logged out.

Upvotes: 3

Michael Meadows
Michael Meadows

Reputation: 28426

Why not set this up to run as a scheduled task? Have it execute and then exit. Set up Windows to start the process as a scheduled task at 3:00 AM daily.

Upvotes: 1

Artelius
Artelius

Reputation: 49109

compare the DateTime.Now with 3am

This is a bad solution, even if you sleep for some time between each check, as it wastes system resources unnecessarily (not only in repeatedly checking the time, but also in the memory usage of the program).

Upvotes: 2

Tomas Aschan
Tomas Aschan

Reputation: 60664

Write a console app or equivalent, and use the Windows Task Scheduler to run it daily.

Upvotes: 4

KB22
KB22

Reputation: 6979

System.Threading.Timer might work out for you.

Documented here

Upvotes: 1

omantn
omantn

Reputation: 21

If you are expecting a file every night, instead of worrying about when it arrives, just get an event fired when it does.

Look at:

System.IO.FileSystemWatcher

File System Watcher on MSDN

Upvotes: 2

Related Questions