1

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);
    }
}
7
  • 3
    You can use Hangfire for this job. Also read this great article from Scott Hanselman. Commented Oct 21, 2016 at 5:29
  • Can it be used with C# back-end as well? @PawełHemperek Commented Oct 21, 2016 at 5:34
  • It can be only used with C# back-end. Read those links carefully and you will be good to go! Commented Oct 21, 2016 at 5:35
  • i am using ASP.net With C# @PawełHemperek Commented Oct 21, 2016 at 5:37
  • Well, okay. So what? Commented Oct 21, 2016 at 5:37

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a specific reason you would keep the background worker in CacheManager and not make it static instead?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.