コンソールプログラムを作成する
新しいWindowsサービスアイテムを作成する
右クリックしてインストーラーを追加します
以下の設定項目を設定してください
//
// serviceInstaller1
//
this.serviceInstaller1.Description = "学习使用服务"; //服务中的描述
this.serviceInstaller1.DisplayName = "TestService"; //服务名称
this.serviceInstaller1.ServiceName = "TestService";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//选择serviceProcessInstaller1项设置 服务为本地服务
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
作成したサービスファイルを開きます
OnStartメソッドに次のコードを記述します
#if DEBUG
if (!Debugger.IsAttached)
Debugger.Launch();
Debugger.Break();
#endif
//启动服务要做什么事情全在这调用
StartWeatherService();
//进行相应的操作
private void StartWeatherService()
{
try
{
LogWriter.Writer(DateTime.Now + ":服务开始启动!");
TestService weatherService = new TestService();
//将服务放入线程池中异步启动
ThreadPool.QueueUserWorkItem((w) => { weatherService.Start(); });
LogWriter.Writer(DateTime.Now + ":服务已经启动!");
}
catch (Exception ex)
{
LogWriter.Writer(DateTime.Now + "异常:" + ex.Message);
}
}
创建 TestService 类
public class TestService
{
//创建定时器
private System.Timers.Timer _Timer;
public void Start()
{
Thread.Sleep(5000);
_Timer = new System.Timers.Timer();
_Timer.Enabled = false;
_Timer.Interval = 10;
_Timer.AutoReset = true;
_Timer.Elapsed += _Timer_Elapsed;
//_Timer.Enabled = true;
}
private void _Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_Timer.Enabled = false;
try
{
LogWriter.Writer(DateTime.Now + ":服务已经启动,正在写入数据!");
}
catch (Exception ex)
{
LogWriter.Writer(DateTime.Now + ":刷新天气失败!" + ex.Message);
}
}
}
最后,在控制台引用程序中加入以下代码
class Program
{
static void Main(string[] args)
{
ServiceBase[] ServicesToRun = new ServiceBase[]
{
new SyncServiceManager()
};
ServiceBase.Run(ServicesToRun);
}
}
安装服务
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
InstallUtil.exe ...\bin\Debug\BackgroundApplicationProgram.exe
卸载服务
sc delete BackgroundApplicationProgram.exe
効果