using AppServerWatchDogService.Enums; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace AppServerWatchDogService { public static class RestartTCPClient { static Timer timer; static Int32 HH = ConfigHelper.SetHour; static Int32 MM = ConfigHelper.SetMinute; static String RestartType = ConfigHelper.SetRestartType; public static void Main() { setup_Timer(HH, MM, RestartType); } public static void setup_Timer(Int32 HH, Int32 MM, String restartType) { AppServerWatchDogService.WriteEventLog(Program.COMPANY, "### Timer Started ###", EventLogEntryType.Information, (Int32)EventId.EVENT_WATCHDOG); DateTime nowTime = DateTime.Now; DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, HH, MM, 0, 0); //Specify your time HH,MM,SS if (nowTime > scheduledTime) scheduledTime = scheduledTime.AddDays(1); if(restartType.Equals("periodic")) scheduledTime = DateTime.Now.AddHours(HH).AddMinutes(MM); AppServerWatchDogService.WriteEventLog(Program.COMPANY, String.Format("TCP Service will restart @ {0}", scheduledTime.ToString()), EventLogEntryType.Information, (Int32)EventId.EVENT_WATCHDOG); double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds; timer = new Timer(tickTime); timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Start(); } static void timer_Elapsed(object sender, ElapsedEventArgs e) { AppServerWatchDogService.WriteEventLog(Program.COMPANY, "### Timer Stopping ###", EventLogEntryType.Warning, (Int32)EventId.EVENT_WATCHDOG); timer.Stop(); AppServerWatchDogService.WriteEventLog(Program.COMPANY, $"### Restarting TCP Service: {ConfigHelper.TCPServiceName}###", EventLogEntryType.Information, (Int32)EventId.EVENT_WATCHDOG); try { if (ServiceControlUtils.IsServiceRunning(ConfigHelper.TCPServiceName)) { ServiceControlUtils.stopService(ConfigHelper.TCPServiceName); ServiceControlUtils.startService(ConfigHelper.TCPServiceName); } else { ServiceControlUtils.startService(ConfigHelper.TCPServiceName); } AppServerWatchDogService.WriteEventLog(Program.COMPANY, $"### Restarted TCP Service: {ConfigHelper.TCPServiceName} ###", EventLogEntryType.Information, (Int32)EventId.EVENT_WATCHDOG); } catch(Exception ex) { AppServerWatchDogService.WriteEventLog(Program.COMPANY, $"Failed to restart TCP Service: {ConfigHelper.TCPServiceName} because: " + Environment.NewLine + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_WATCHDOG); } setup_Timer(HH, MM, RestartType); } } }