How to Create and Use a Windows Service

SOURCE CODE

protected override void OnStart(string[] args)
{
    Thread startThread = new Thread(new ThreadStart(ScheduleService));
    startThread.Start();
}
public void ScheduleService()
{
    try
    {
        ScheduleTimer = new Timer(new TimerCallback(SendMail));
        DateTime scheduleTime = DateTime.MinValue;
        scheduleTime = DateTime.Parse("4:09 PM");
        if (DateTime.Now > scheduleTime)
            scheduleTime = scheduleTime.AddMinutes(5);
        TimeSpan timeSpan = scheduleTime.Subtract(DateTime.Now);
        int dueMilli = Convert.ToInt32(timeSpan.TotalMilliseconds);
        ScheduleTimer.Change(dueMilli, Timeout.Infinite);
    }
    catch(Exception ex)
    {
        WriteErrorLog(ex);
    }
}
public void SendMail(object e)
{
    try
    {
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress("dare2doengineering@gmail.com");
            mail.To.Add("dare2doengineering@gmail.com");
            mail.Subject = "Hello Service";
            mail.Body = "Hello Service";
            using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
            {
                smtp.Credentials = new NetworkCredential("dare2doengineering@gmail.com", "");
                smtp.EnableSsl = true;
                smtp.Send(mail);
                WriteErrorLog("Mail Sent " + DateTime.Now);
            }
            this.ScheduleService();
        }
    }
    catch (Exception ex)
    {
        WriteErrorLog(ex);
    }
}
public static void WriteErrorLog(Exception ex)
{
    StreamWriter sw = null;
    try
    {
    	sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
        sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
        sw.Flush();
        sw.Close();
    }
    catch
    {
    }
}                                                                          
public static void WriteErrorLog(string Message)
{
    StreamWriter sw = null;
    try
    {
    	sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
        sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
        sw.Flush();
        sw.Close();
    }
    catch
    {
    }
}                               
protected override void OnStop()
{
    ScheduleTimer.Dispose();
}

SOURCE VIDEO

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top