简体   繁体   中英

System.Timers.Timer for long time intervals

Is System.Timers.Timer good enough for invoking a method in longer time intervals? Ie for daily jobs and similar things. Is something better out there what I should use for something like that?

Example:

System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoTimedWork);
timer.Interval = 1000 * 60 * 60 * 24; // 24 Hours
timer.Start();

Thanks!

How is your application process initiated? Using a System.Timers.Timer with a 24-hour interval is fine, provided you can guarantee your process will still be alive to handle the timer callback - your process might have a memory-leak or resource-leak that causes the OS to kill it, or it might be hosted in an environment that routinely "recycles" processes (such as Application Pools in IIS).

A better solution would be to have both: start the timer in your application, but also have a cron-job ("Scheduled Task" on Windows) that will start your program if it isn't already running - you can use a systemwide named mutex and other IPC means to ensure only 1 instance of your application runs at a time.

As long as your process is actually alive during this time (for example because it's a windows service) then a timer is fine.

If you need to do something at a specified time and cannot guarantee your process is running, using the Windows Task Scheduler might be a good option.

If you need more options, you might want to look into scheduling libraries like Quartz .

I use Hangfire for it. There are awesome features, like Fire-and-forget tasks, delayed tasks, recurring tasks. Background jobs are saved into a persistent storage like SQL Server, Redis, PostgreSQL, MongoDB and others. You can run it as a console application, Windows Service, Azure Worker Role, etc. Also is open source and completely free for commercial use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM