using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using ComputerBLL;
using ComputerLibrary;
using System.Threading;
namespace ComputerNetworkMonitoringService
{
/// <summary>
/// 服务名称:Network Monitoring Service
/// 执行脚本
/// 安装:
/// 卸载:
/// </summary>
public partial class MonitoringService : ServiceBase
{
Thread threadforwork;
public MonitoringService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (threadforwork == null)
{
threadforwork = new Thread(DoWork);
}
threadforwork.IsBackground = true;
threadforwork.Start();
WorkLog("服务已开启!");
}
protected override void OnStop()
{
if (threadforwork != null)
{
if (threadforwork.ThreadState == System.Threading.ThreadState.Running)
{
threadforwork.Abort();
}
}
WorkLog("服务已停止!");
}
private void DoWork()
{
string frequencyConfig = System.Configuration.ConfigurationSettings.AppSettings["Frequency"];
int frequency = 0;
int.TryParse(frequencyConfig, out frequency);
while (true)
{
string name = ComputerInfo.Name;
string mac = ComputerInfo.MAC;
string ip = ComputerInfo.PublicNetworkIP;
try
{
ComputerInfoBLL.InsertOrUpdate(ip, mac, name);
}
catch (Exception)
{
}
Thread.Sleep(frequency * 60 * 1000);
}
}
private void WorkLog(string msg)
{
Utilities.WriteLog(System.AppDomain.CurrentDomain.BaseDirectory + "Log", "服务工作状态.txt", "【创建时间" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now) + "】:"+msg);
}
}
}
注意: thread 可以解决服务应答超时问题。
安装服务的批处理代码:
v2.0.50727
@echo 服务器网络监控服务正在安装……
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\installutil.exe ComputerNetworkMonitoringService.exe
Net Start "Network Monitoring Service"
sc config "Network Monitoring Service" start= auto
pause
v4.0.30319
@echo 服务器网络监控服务正在安装……
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe ComputerNetworkMonitoringService.exe
Net Start "Network Monitoring Service"
sc config "Network Monitoring Service" start= auto
pause
卸载服务的批处理代码:
v2.0.50727
@echo 服务器网络监控服务正在卸载……
Net Stop "Network Monitoring Service"
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\installutil.exe /u .\ComputerNetworkMonitoringService.exe
pause
v4.0.30319v4.0.30319v4.0.30319
@echo 服务器网络监控服务正在卸载……
Net Stop "Network Monitoring Service"
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u .\ComputerNetworkMonitoringService.exe
pause