C# - Task Scheduling
I am using Asp.Net - Web Forms - Framework 3.5
I want to send emails to web-site users at 12am mid night. I have made a class method that sends emails but what is best way to auto execute it at 12 mid night?
In开发者_Python百科 linux we have cron jobs, what's on windows both dedicated and shared server?
Simplest way is to write a little command line app that sends emails, then use Windows Task Scheduling to run the app every day at midnight.
As a cron
substitute you can try at
command and run some executable which will send e-mails, or you can create a windows service to do this job.
When on a shared host, with no access to the task scheduler, I've often times put some code in the Global.asax, which would create a new static Timer object in the OnStart of the application. I would then run my class method every hour or so, when the Timer elapsed.
The downside to this, is that you have to keep your application pool running 24/7, otherwise it will spin down and your code won't run hourly.
An alternative, would be to make a page that runs the code from your class method, and trigger that page from an external source automatically at midnight each night. You could just setup a wget/curl script to hit that URL programmaticly.
Lastly, you have other solutions, as detailed in this other post: Can you run a "service" that runs a scheduled task from an ASP.Net project?
Writing a windows service calling the code periodically for sending emails would do the job.
You can use task scheduler which is the winnows equivalent of chron, or you can write a windows service that periodically checks the time and if it's after midnight, it can send emails.
You can't do this from your web form because that code only executes when a user is on the site, and it's very bad practice to leave a thread running; iis would probably recycle it anyway.
I've had some success using Quartz.NET, but the task scheduler and simple command line app combination as suggested by others is the simplest way to do it.
Create your application in windows service and in app.config file use timer and set the timer to 12 midnight.
If you need to run a scheduled task/cron job in a shared hosting environment, you'll find a list of free web cron job providers here: ASP.NET: Free scheduling of your tasks (Cron jobs)
精彩评论