.net - Aktiver timer for en bestemt begivenhed, der skal udføres med et interval i C #

Indlæg af Hanne Mølgaard Plasc

Problem



Jeg opretter en windows service til at sende mail ved bestemte tidsintervaller. Jeg vil aktivere en timer til at arbejde en mail\_send().


private void timer1(object sender, EventArgs e) {
    // I need a code here to work with email\_send()
    timer1.Elapsed += new ElapsedEventHandler(email\_send);
}

public void email\_send(object sender, System.Timers.ElapsedEventArgs e) {
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("email from");
    mail.To.Add("emailto");
    mail.Subject = DateTime.Now +"logfile";
    mail.Body = "mail with log file attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("F:\logfile\logfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("emailfrom", "password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);
}

Bedste reference


Du skal køre din timer ved at kalde metode Start () for at 'aktivere' den.


private void timer1(object sender, EventArgs e)
{
    timer1.Elapsed += new ElapsedEventHandler(email\_send);
    timer1.Start();
}

Andre referencer 1


Først Initialiser timeren


public static void Main()
{
InitializeTimer();
timerr.Start();
}


Du kan bruge Start og stop for at starte timeren og Stop timmeren


private void InitializeTimer()
 {
  Timer timerr = new Timer();
  timerr.Interval = 5000;
  timerr.Tick += Timerr\_Tick;
  }


Skriv derefter tick event.


private void Timerr\_Tick(object sender, EventArgs e)
    {
         MailMessage mail = new MailMessage();
         SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
          mail.From = new MailAddress("email from");
         mail.To.Add("emailto");
         mail.Subject = DateTime.Now +"logfile";
         mail.Body = "mail with log file attachment";

         System.Net.Mail.Attachment attachment;
         attachment = new System.Net.Mail.Attachment("F:\logfile\logfile.txt");
         mail.Attachments.Add(attachment);

         SmtpServer.Port = 587;
         SmtpServer.Credentials = new System.Net.NetworkCredential("emailfrom", "password");
         SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);
}