我是C#和麪向對象編程的新手。我正在創建一個windows服務,每隔10分鐘就會ping一次IP地址10次。C# - Windows服務 - 連續Ping請求超時
如果10個請求中有7個超時(Isolate Network Blips),它會發送一封電子郵件通知系統關閉。我有這部分權利。
我面臨的問題是通知說系統已啓動。
以下是我的代碼:
protected override void OnStart(string[] args)
{
eventLog.WriteEntry("Source: Service Started",EventLogEntryType.SuccessAudit);
timer.Enabled = true;
timer.Interval = (10 * 60 * 1000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(methodStart);
}
public void methodStart(object sender, ElapsedEventArgs e)
{
Ping p = new Ping();
PingReply r;
string s = "SYSTEM-IP-ADDRESS";
int upCounter=0;
int downCounter = 0;
bool sysDown = false;
try
{
for (int i = 0; i < 10; i++)
{
r = p.Send(s);
if (r.Status == IPStatus.Success)
{
eventLog.WriteEntry("Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n", EventLogEntryType.SuccessAudit);
upCounter++;
}
else
{
downCounter++;
}
}
if(downCounter>=7)
{
//LOG ENTRY
eventLog.WriteEntry("Unable to reach the system after 7 Timeouts! Email notification Sent.", EventLogEntryType.FailureAudit);
// EMAIL NOTIFICATION
downCounter = 0;
}
else
{
sysDown = false;
}
}
catch (Exception ex)
{
//EXCEPTION HANDLING
}
loopCounter++;
if(sysDown==false && loopCounter>2)
{
eventLog.WriteEntry("The Tool Is Up Email Notification Sent", EventLogEntryType.SuccessAudit);
// EMAIL NOTIFICATION
loopCounter = 0;
}
}
我所試圖實現的是,在Ping超時7 =>時間(s),併發送電子郵件通知,說明它已關閉。如果系統在接下來的兩次執行過程中啓動,請發送一封電子郵件,說明系統已啓動(我的代碼每兩次執行一次會發送一封電子郵件,說明系統已啓動)。
這是如何實現的?
更新1:我有電子郵件邏輯。
更新2:Vibhav Ramcharan的解決方案觸發系統在每次執行startMethod()時發出通知。
系統關閉通知的閾值爲70%,這是單次執行期間連續7次ping故障。
假設系統停機。觸發一封電子郵件,通知系統故障。
當系統啓動時,執行成功執行兩次。發送電子郵件通知系統已啓動。
上面的代碼會觸發每個methodStart()上的系統電子郵件。最終,垃圾郵件。
不,我有電子郵件邏輯工作。我所追求的是在系統關閉後執行兩次方法的邏輯。 – Tango