protected override void OnStart(string[] args) { DailyMailService mailScheduler = new DailyMailService(); WriteToFile("DailyMailSender started"); SheduleService(); }
public static void SheduleService() { try { DailyMailService mailScheduler = new DailyMailService(); scheduler = new Timer(new TimerCallback(ShedularCallBack)); string mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); WriteToFile("DailyMailSenderLog Mode: " + mode + " " + "{0}"); //setting default value. DateTime scheduledTime = DateTime.MinValue; var statusReportExcel = CreateStatusSpreadSheet(GetStatusReports()); mailScheduler.SendMail("*****@*****.**", "*****@*****.**", "Daily Status report", "PFA the status report for the day", statusReportExcel); if (mode == "DAILY") { //Get the Scheduled Time from AppSettings. scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { //Get the Interval in Minutes from AppSettings. int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); //Set the Scheduled Time by adding the Interval to Current Time. scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); WriteToFile("DailyMailSenderService scheduled to run after: " + schedule + " {0}"); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); scheduler.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { WriteToFile("DailyMailSenderService Error on: {0} " + ex.Message + ex.StackTrace); //Stop the Windows Service. } }