咱们有时候可能会想要作一些定时任务,例如每隔一段时间去访问某个网站,或者下载一些东西到咱们服务器上等等之类的事情,这时候windows service 是一个不错的选择。windows
一、打开Visua studio2013新建一个windows Service程序,我命名为TimerService服务器
注意,这里的.NET Framwork框架的选择要与你电脑上的框架一致,我这里选择的是4.0框架
二、在Service1设计器中右击空白处选择查看代码ide
3.在Service1.cs中设定定时的时间间隔以及定时执行的任务这里的Onstart方法定义定时器的开始执行,执行的时间间隔,以及时间间隔达到后所要执行的方法,我这里是执行了一个文件写入的方法,代码以下工具
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Timers; namespace TimerService { public partial class Service1 : ServiceBase { Timer timer; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new Timer(1000); timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed); timer.Start(); WriteLog("服务启动"); } protected override void OnStop() { timer.Stop(); timer.Dispose(); WriteLog("服务中止"); } protected void Timer_Elapsed(object sender, ElapsedEventArgs e) { WriteLog("服务执行中"); } protected void WriteLog(string str) { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log.txt"; StreamWriter sw = null; if (!File.Exists(filePath)) { sw = File.CreateText(filePath); } else { sw = File.AppendText(filePath); } sw.Write(str + DateTime.Now.ToString() + Environment.NewLine); sw.Close(); } } }
四、在Service1设计器中右击空白处,选择添加安装程序,会添加一个ProjectInstaller设计器网站
五、在ProjectInstaller设计器中选择serviceProcessInstaller,右击查看属性,将Account的值改成LocalSystemspa
六、在ProjectInstaller设计器中选择serviceInstaller1,右击查看属性,这里的ServiceName就是要在服务器的服务中显示的名称,我将其命名我TimerServicedebug
七、右击解决方案,点击生成解决方案设计
一、打开刚刚新建建项目所在的文件夹,找到bin文件下面的debug文件夹,即D:\用户目录\个人文档\Visual Studio 2013\Projects\TimerService\TimerService\bin\Debug,里面有个TimerService.exe应用程序,就是咱们所要执行的项目code
二、打开文件夹C:\Windows\Microsoft.NET\Framework\v4.0.30319,能够看到里面有一个InstallUtil.exe的应用程序,这就是咱们要的安装工具,这里的Framework的版本与咱们项目的Framework版本保持一致
三、打开cmd输入cd C:\Windows\Microsoft.NET\Framework\v4.0.30319指令,而后再输入InstallUtil D:\用户目录\个人文档\Visual~1\Projects\TimerService\TimerService\bin\Debug\TimerService.exe,便可完成安装
四、启动任务管理器,点击服务,找到名称TemrService的服务,右击启动,便可将建立的定时服务启动,这里的服务名称就是咱们在项目的serviceInstaller1的属性里面设置的serviceName
五、在咱们的D:\用户目录\个人文档\Visual Studio 2013\Projects\TimerService\TimerService\bin\Debug文件下面会发现多了一个log.txt的文件,就是咱们在项目中建立的文件,打开便可看到项目正常执行
要卸载应用服务也很简单,只须要在cmd中输入如下指令便可
InstallUtil /u D:\用户目录\个人文档\Visual~1\Projects\TimerService\TimerService\bin\Debug\TimerService.exe