Home > Software design >  How to ping different devices at different time intervals efficiently
How to ping different devices at different time intervals efficiently

Time:01-03

I am trying to create an application that pings the devices configured by the user and reflects the status online or offline. A user can specify IP and Ping Interval for a device and based on that configuration the application needs to ping the device. For example, if the user specifies IP 198.67.227.143 and Ping Interval as 5 seconds, then the application will ping 198.67.227.143 every 5 seconds and reflect the status of whether the device is online or offline.

There can be multiple devices with different ping intervals configured. For example, Device A has a ping interval of 10 seconds and Device B has a ping interval of 20 seconds.

I want to know what is the best way to check whether a device should be pinged or not. Currently, the solution I can come up with is setting up a process that runs every second and loops through all the configured devices and checks if the device should be pinged or not based on the LastPingTime of the device.

Is there a better way of approaching this problem? I am trying to accomplish this in C# and .NET 4.6.2.

CodePudding user response:

One option you can try to have different timers for reach devices, you don't need to ping every second for each device.

I have done simple basic implantation for this, you can use this concept in your code.

//each device representation
public class Device
{
    public string IpAddress { get; set; }
    public int PingInterval { get; set; }
    public Timer PingTimer { get; set; }
    public bool IsOnline { get; set; }
}

public class DeviceManager
{
    private List<Device> _devices;

    public DeviceManager()
    {
        _devices = new List<Device>();
    }

    public void AddDevice(string ipAddress, int pingInterval)
    {
        var device = new Device
        {
            IpAddress = ipAddress,
            PingInterval = pingInterval
        };

        device.PingTimer = new Timer(OnPingTimerElapsed, device, TimeSpan.Zero, TimeSpan.FromSeconds(pingInterval));

        _devices.Add(device);
    }

    private void OnPingTimerElapsed(object state)
    {
        //you can log the device state at this place
        var device = (Device)state;

        // ping and update the status of the device
        device.IsOnline = SendPing(device.IpAddress);
    }

    private bool SendPing(string ipAddress)
    {
        //ping logic implementation;
    }
}

you can call like this.

DeviceManager deviceManager = new DeviceManager();
deviceManager.AddDevice("10.220.63.36", 5);
deviceManager.AddDevice("10.220.63.37", 10);
  • Related