2016-10-21 1 views
1

내가보고있는 페이지에 관계없이 백그라운드에서 자동으로 실행해야하는 코드가 있습니다. 예를 들어 내가 홈페이지에있는 경우 또는 페이지 웹 사이트에서 코드가 자동으로 실행되기를 원합니다. 정확히 말하면 내가 작성한 이메일 수업에서 30 분마다 이메일 알림을 보내려고합니다. 나는 비슷한 일이 Windows 서비스를 통해 이루어질 수 있다는 것을 알고 있지만 코드가 웹 사이트에 있기를 원합니다. DOT.NET 세계 비동기 호출에서ASP.net 웹 사이트에서 자동으로 작업 수행 C#

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); 
    } 
} 
+3

이 작업에는 [Hangfire] (http://hangfire.io/)를 사용할 수 있습니다. Scott Hanselman의 [이 훌륭한 기사] (http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx)도 읽어보십시오. –

+0

C# 백엔드에서도 사용할 수 있습니까? @ PawełHemperek – johnnitro

+0

C# 백엔드에서만 사용할 수 있습니다. 신중하게 그 링크를 읽고 당신은 잘 갈 것입니다! –

답변

2

는 등 AsyncHandlers

는 여기에 "BackgroundWorker에"를 사용할 수 있습니다 AJAX와 같은 여러 가지 방법으로 수행 할 수 있습니다. 귀하의 경우에는이 당신을 도와줍니다

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(); 
    } 
} 

희망 ...

+0

백그라운드 작업자를 CacheManager에 유지하고 대신 정적이 아닌 특별한 이유가 있습니까? –

0

당신이 당신을 도울 것입니다

var timer = new System.Threading.Timer((e) => 
{ 
    sendEmail(string emailTo, string subject, string body); 
}, null, 0, TimeSpan.FromMinutes(5).TotalMilliseconds); 

희망을 threding 사용하여 다음과 같은 코드를 시도 할 수 있습니다.

관련 문제