1.在VS2010建立windows service工程windows
文件---新建---项目----windows服务。ide
2.双击service1.cs,在onstart中写具体代码,注意若是代码执行须要很长时间,则须要将方法放在子线程中,不然windows服务会启动不起来。工具
protected override void OnStart(string[] args) { try { log4.Info("服务已启动:"); ExecuteTimerTask(); } catch (Exception ex) { log4.Error("服务启动失败", ex); } }
3.定时器Quartz的使用ui
public void ExecuteTimerTask() { //初始化委托变量 TimerTaskDelegate task = new TimerTaskDelegate(SpaceTask); //建立定时任务线程并启动 Thread ThreadTimerTask = TimerTask.CreateTimerTaskThread(task); ThreadTimerTask.IsBackground = true; ThreadTimerTask.Start(); log4.Info("定时任务已启动:"); }
4.添加安装程序spa
在PageRequestService.cs[设计]右键---添加安装程序,会出现线程
注意:account选择localhost ;StartType选择Automatic(开机自动执行)设计
5.安装服务调试
管理员身份运行cmd,执行如下命令日志
开始-运行-cmdcode
安装命令
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PageRequestService\PageRequestService.exe
卸载命令
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PageRequestService\PageRequestService.exe -u
在控制面板---管理工具-----服务----右键----启动服务
6.异常状况
若是不能正常启动服务,说明服务有错误。能够利用“日志查看器”查看错误信息。(调试比较麻烦)。
注意每次对服务改动的话,都必须从新安装。
安装时报错以下:
An exception occurred during the Install phase.
System.InvalidOperationException: Cannot open Service Control Manager on computer '.'. This operation might require other privileges.
The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: 拒绝访问。.
The Rollback phase of the installation is beginning.
See the contents of the log file for the C:\PageRequestService\bin\Debug\PageRequestService.exe assembly's progress.
The file is located at C:\PageRequestService\bin\Debug\PageRequestService.InstallLog.
The Rollback phase completed successfully.
The transacted install has completed.
因为自动写系统日志时出错(例如没有权限),所以将WindowsService的AutoLog属性设为false,便可完成安装。
源码下载:WinService Source