7

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Bigballs
  • 3,729
  • 10
  • 30
  • 27

6 Answers6

4

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
3

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
pavium
  • 14,808
  • 4
  • 33
  • 50
  • This is what I'm thinking...I've try the scheduled task and after the server reboot nothing start... Thank you! – Bigballs Sep 03 '09 at 13:49
  • I must say, I have never had the issue myself. Always worked 100% for me. – Kyle Rosendo Sep 03 '09 at 13:52
  • I'm fairly certain that even back in 2009 (Windows Vista/Server 2008 R2 era) there was an option in Windows Task Scheduler to have tasks run whether a user was logged in or not. – TylerH Aug 21 '23 at 14:13
2

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).

TylerH
  • 20,799
  • 66
  • 75
  • 101
Artelius
  • 48,337
  • 13
  • 89
  • 105
2

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

Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118
omantn
  • 21
  • 1
1

System.Threading.Timer might work out for you.

Documented here

Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118
KB22
  • 6,899
  • 9
  • 43
  • 52
1

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Michael Meadows
  • 27,796
  • 4
  • 47
  • 63