How to execute code in c# service one time per day at the same hour?

时光毁灭记忆、已成空白 提交于 2019-11-28 08:43:11

Write a console app or equivalent, and use the Windows Scheduler (or whatever it's called nowadays...) to run it daily.

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

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

I disabled automatic updates - Windows should ASK first.

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

Other answers are good. I just thought I'd point out that

compare the DateTime.Now with 3am

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

omantn

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

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.

KB22

System.Threading.Timer might work out for you.

Documented here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!