Reputation: 343
I have a piece of code that I need to be run automatically in the background regardless of the page I am viewing. For example if I am in the homepage or about page of a website I want a piece of code to still run automatically. To be precise I want to send a email notification every 30 minutes from the email class that I have made. I am aware that similar thing can be done via windows service but I want the code to be in the website.
public class Email
{
string emailFrom = "[email protected]";
string password = "yourpassword";
string smtpServer = "smtp.gmail.com";
int port = 587;
public void sendEmail(string emailTo, string subject, string body)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(emailFrom);
msg.To.Add(emailTo);
msg.Subject = subject;
msg.Body = body;
SmtpClient sc = new SmtpClient(smtpServer);
sc.Port = port;
sc.Credentials = new NetworkCredential(emailFrom, password);
sc.EnableSsl = true;
sc.Send(msg);
}
}
Upvotes: 1
Views: 134
Reputation: 274
In your case you can try following code using threding
var timer = new System.Threading.Timer((e) =>
{
sendEmail(string emailTo, string subject, string body);
}, null, 0, TimeSpan.FromMinutes(5).TotalMilliseconds);
Hope this will help you.
Upvotes: 1
Reputation: 81
In DOT.NET world Asynchronous invocations can be done in many ways like AJAX, AsyncHandlers etc.
Here you can use "BackgroundWorker".
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.WorkerReportsProgress = false;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
//Add this BackgroundWorker object instance to the cache (custom cache implementation)
//so it can be cleared when the Application_End event fires.
CacheManager.Add("BackgroundWorker", worker);
// Calling the DoWork Method Asynchronously
worker.RunWorkerAsync(); //we can also pass parameters to the async method....
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
// You code to send mail..
}
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if (worker != null)
{
// sleep for 30 minutes and again call DoWork to send mail.
System.Threading.Thread.Sleep(3600000);
worker.RunWorkerAsync();
}
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
//If background worker process is running then clean up that object.
if (CacheManager.IsExists("BackgroundWorker"))
{
BackgroundWorker worker = (BackgroundWorker)CacheManager.Get("BackgroundWorker");
if (worker != null)
worker.CancelAsync();
}
}
Hope this helps you...
Upvotes: 2