using langguanApi.Extensions.AutoDI; using System.Net.NetworkInformation; namespace langguanApi.Service { /// /// ping service /// public class PingService { private DeviceService _deviceSerive; /// /// /// /// public PingService(DeviceService deviceSerive) { _deviceSerive = deviceSerive; } /// /// /// public void CreatTask() { //5分钟执行一次 Timer myTimer = new Timer(new TimerCallback(Execute), null, 2000, 300000); // Timer myTimer = new Timer(new TimerCallback(Execute), "ping service", 2000, 10000); } /// /// /// /// public async void Execute(object b) { var deviceList = await _deviceSerive.GetAsync(); if (deviceList.Any()) { foreach (var item in deviceList) { if (!string.IsNullOrEmpty(item.Ip)) { var ip = item.Ip.Split(":")[0]; var res = await PingIp(ip); item.state = res == true ? 1 : 0; await _deviceSerive.UpdateAsync(item.Id, item); } } } Console.WriteLine("{0} ping running.", (string)b); } /// /// ping /// /// /// public async Task PingIp(string ip) { try { //Ping 实例对象; Ping pingSender = new Ping(); PingReply pingReply = await pingSender.SendPingAsync(ip); if (pingReply.Status == IPStatus.Success) { return true; } } catch (Exception) { return false; } return false; } } }