C# - Windows服务 - 连续Ping请求超时

时间:2017-07-12 16:44:23

标签: c# service windows-services

我是C#和面向对象编程的新手。我正在创建一个Windows服务,它会每10分钟ping一次IP地址10次。

如果10个请求中有7个请求超时(隔离网络闪烁),它将发送一封电子邮件通知系统已关闭。我有这个部分。

我面临的问题是通知系统已启动。

以下是我的代码:

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 =&gt;时间并发送一封电子邮件,说明它已关闭。如果系统在接下来的2次执行期间启动,请发送一封电子邮件,说明系统已启动(我的代码每2次执行一次电子邮件,说明系统已启动)。

如何实现这一目标?

更新1 :我有电子邮件逻辑。

更新2 :Vibhav Ramcharan的解决方案会在每次执行 startMethod()时触发系统通知。

System Down通知的阈值为70%,即一次执行期间连续7次ping失败。

假设系统出现故障。触发电子邮件将通知系统故障。

系统启动时,执行成功两次。发送电子邮件通知系统已启动。

以上代码会在每个 methodStart()上触发系统电子邮件。最终,垃圾邮件。

3 个答案:

答案 0 :(得分:0)

好的,阅读你的评论我认为你需要在方法之外声明的静态int。 例如:

class Program{

     private static int loopCounter = 0;
     static void Main(string[] args)
     {
          // code
     }

     public void methodStart(object sender, ElapsedEventArgs e){
         // code
     }

}

如果需要执行两次方法,则应该从methodStart中提取所有方法(示例名称:startUpMethod(),然后在methodStart中调用startUpMethod()); 当你想再次调用该方法时(如果它在同一方法内部无关紧要),你再次调用startUpMethod()。 这称为递归调用。 实施例。

 public void public void methodStart(object sender, ElapsedEventArgs e){
     startUpMethod();
 }

 public void startUpMethod()
 {
      //do something
      if(repeat)
         startUpMethod()
 }

你应该照顾无限循环

答案 1 :(得分:0)

根据我的理解,您需要跟踪两次成功执行并在失败后发送电子邮件。我在下面的代码中添加了评论。

    protected override void OnStart(string[] args){

        var timer = new Timer
        {
            Enabled = true,
            Interval = (10 * 60 * 1000)
        };
        timer.Elapsed += new System.Timers.ElapsedEventHandler(methodStart);
    }

    private int loopCounter = 0;
    bool sysDown = false;

    // Used to count the number of successful executions after a failure.
    int systemUpAfterFailureCount = 0;

    public void methodStart(object sender, ElapsedEventArgs e)
    {

        Ping p = new Ping();
        PingReply r;
        string s = "SYSTEM-IP-ADDRESS";
        int upCounter = 0;
        int downCounter = 0;


        try
        {
            for (int i = 0; i < 10; i++)
            {
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                    upCounter++;
                else
                    downCounter++;
            }

            if (downCounter >= 7)
            {
                // LOG ENTRY
                // EMAIL NOTIFICATION
                downCounter = 0;
                // The system has failed
                sysDown = true;
            }
            else
            {
                // Before changing the sysDown flag, check if the system was previously down
                // This is the first successful execution after the failure
                if (sysDown)
                    systemUpAfterFailureCount++;

                // This will allow systemUpAfterFailureCount to increase if it is Ex: 1 and sysDown = false (Your success execution limit is 2, which we control at the IF block below)
                if (systemUpAfterFailureCount > 1)
                    systemUpAfterFailureCount++;

                sysDown = false;
            }

        }
        catch (Exception ex)
        {
            //EXCEPTION HANDLING
        }

        loopCounter++;

        // Check if the system is down, if it is up execute the following code for a maximum of 2 executions.
        if (sysDown==false && systemUpAfterFailureCount <= 2) 
        {
            // LOG ENTRY
            loopCounter = 0;

            // Send email for successful executions after a failure, limited to 2.
            if (systemUpAfterFailureCount <= 2)
            {
                // EMAIL NOTIFICATION
            }

            // After two successful executions have occured, reset the counter
            if (systemUpAfterFailureCount == 2)
            {
                systemUpAfterFailureCount = 0;
            }
        }
    }

答案 2 :(得分:0)

以下代码有效且需要。

 public void methodStart(object sender, ElapsedEventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s = "SYSTEM-IP-ADDRESS";
                try
                {
                    for (int i = 0; i < 10; i++)
                    {
                        r = p.Send(s);
                        if (r.Status == IPStatus.Success)
                        {
                             SuccessNoti();

                       }
                        else
                        {

                            UnsuccessfulNoti();
                        }
                    }
                }
                catch (Exception ex)
                {
                    UnsuccessfulNoti();
                }

                }

            } 

             public void SuccessNoti()
            {
                if ((string.Compare(status, "Down", false) == 0) && Successcount >= 7)
                {
                    using (MailMessage mail = new MailMessage())
                    {
                        using (SmtpClient SmtpServer = new SmtpClient(smtp))
                        {
                        //  EMAIL NOTIFICATION

                            Successcount = 0;
                            status = null;
                        }
                    }
                }
                else
                {
                    if (string.Compare(status, "Down", false) == 0)
                    {
                        Successcount = Successcount + 1;
                    }
                }
            }

             public void sendfailureNotofication()
            {
                if (failureCount >= 7 && !(string.Compare(status, "Down", false) == 0))
                {

                    status = "Down";
                    using (MailMessage mail = new MailMessage())
                    {
                        using (SmtpClient SmtpServer = new SmtpClient(smtp))
                        {
                        //  EMAIL NOTIFICATION

                            failureCount = 0;
                            status = "Down";
                        }
                    }
                }
                else
                {
                    if (!(string.Compare(status, "Down", false) == 0))
                    {
                        failureCount = failureCount + 1;
                    }
                }


            }