I make a site on ASP.NET MVC, it is necessary to make it so that at a certain time on a clock, for example, at 20:20 a certain function starts up, in my case of mail distribution.

Can this be done by system tools or use third-party libraries?

I would like this functionality: For a given key, I add the launch of my function for a certain time. I can hang a lot of these functions at different times. If necessary, I can detach the launch using the key.

  • @VladD is not quite - in asp.net tight with long-lived threads, so the solutions for the links are not suitable. - PashaPash
  • @PashaPash: There are solutions with await, the flow, in theory, is not needed. But if the process can be killed, this is a problem, of course. - VladD
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

There is no reliable way to run something at a certain time in ASP.NET MVC. There is not even a reliable way to run something in the background thread.

The cause of insecurity is the completely external control of the lifetime of the application. Those. if IIS wants to kill or put to sleep your application due to user inactivity, memory overruns, just on schedule, for any other reason - it will kill. And no code that will have to work in the hour X - will not work.

In addition, with certain settings, IIS can run two or more simultaneous processes for the same application, and your code to run on a schedule will run twice.

Reliable ways:

  • To carry out processing almost in windows service where it is possible to organize the reliable timer.
  • Deliver mail processing in the console application, put it to execution in the Task Scheduler.
  • Leave mail processing in ASP.NET / MVC, but link it to a specific url. Make a simple Windows Service / Console + Task Scheduler / use ready-made jobs from your hoster to call this url.
  • one
    Thanks for the answer. I decided to use this library here - hangfire.io , while there is no guarantee that it will work 100% in time, but I think this is not critical. The site uptime will be high. I also think to ask the host to make the setting so that the site application does not turn off - startMode = "AlwaysRunning" - Dmitry Polyanin

And why to attract this site? For such things there is, for example, the standard Windows Task Scheduler, through which you run, for example, a self-written program.

You can continue to dream:

  1. Make a controller with special functions that will be called special. Windows service and return something for analysis. The plus is that the whole web code in one project.
  2. In the ApplicationStart application, call a separate thread (thread) with a child function in which to set a timer with an action. Not tested, but in theory should work ...
  • So I did not do this for this site. Just mailing need for the site. - Dmitry Polyanin
  • probably will help, added. - evgnib