Reputation: 173
I am trying to send an email every day in specific time, but seems like the function(void SomeMethodRunsAtSpecificTime(object o)) in System.Threading.TimerCallback is not working.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
double TimeOfExecution = 14;
DateTime now = DateTime.Now;
DateTime today7am = now.Date.AddHours(TimeOfExecution);
DateTime next7am = now <= today7am ? today7am : today7am.AddDays(1);
System.Threading.TimerCallback callback = new
System.Threading.TimerCallback(SomeMethodRunsAtSpecificTime);
var timer1 = new System.Threading.Timer(callback, null, next7am - DateTime.Now, TimeSpan.FromHours(24));
}
void SomeMethodRunsAtSpecificTime(object o)
{
//Sending email from someone to someone(this function has no problem)
}
Upvotes: 0
Views: 600
Reputation: 29207
As soon as Page_Load
is done executing the Timer
goes out of scope. It's the same as if you declared an int
in that method. Once the method is done executing, where does the int
go? Nowhere. It's gone.
Even if you made the Timer
a property of the page (the _Default
class) the same is true. The whole class is created just to generate a response (HTML page) and then it also goes out of scope, taking its member variables with it.
A web application isn't really a good tool for doing something at regular intervals. Its purpose is to respond to requests when they come in. When there are no requests the application isn't doing anything except waiting for requests. If no one sends a request to the site for a while the whole application can even shut down, and IIS just starts it up later when a request comes in.
To do something at regular intervals you may want a Windows Service or even a scheduled task.
Upvotes: 1