0

Is System.Timers.Timer good enough for invoking a method in longer time intervals? I.e. 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!

DDan
  • 8,068
  • 5
  • 33
  • 52

3 Answers3

2

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • It's an application server under IIS, so IIS will eventually recycle it and I lose my timer instance? – DDan Mar 10 '16 at 09:33
  • 1
    @DDan Correct. You should look at alternatives. IIS Worker processes are not appropriate for regularly-scheduled tasks. – Dai Mar 10 '16 at 17:58
  • I have to use IIS because of certain reasons. I added to App_Start an initializer code to start my timer, and whenever the application pool recycles it also invokes App_Start. This way I can ensure that it is always set. – DDan Mar 28 '16 at 09:21
1

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

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

Community
  • 1
  • 1
Toddams
  • 1,489
  • 15
  • 23