在项目中经常需要定时执行一些任务,在linux系统中,crontab命令能够灵活的设置程序执行方案,而windows也有类似的功能——设置计划任务,或者编写windows服务程序。因为windows服务程序支持开机启动,可靠性高,灵活等优点,所以我们一直用它。
开始打开vs2010,在文件菜单中选择新建,再选择项目,在跳出来的对话框中选择Windows下的Windows服务。
填好你的项目名称后按确定,系统会自动帮你生成一些东西
Program.cs文件的内容是这样的
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace MyWindowsService { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } } }
而Service1.cs则是windows服务的主程序,所有的执行策略都应该是在这里面设定的。通常的做法是在Service1的设计页面中添加一个计时器控件,注意到这个控件的命名空间是System.Windows.Forms.Timer,网上有人说这个计时器不稳定,相比之下System.Timers.Timer会更好一点。这个控件不在工具栏中,需要在工具栏的组件中点击右键,在弹出菜单中选择选择项,在.net framework的选项中找到System.Timers的Timer,打钩然后确定即可添加到工具栏中。不过我这里不用计时器控件。代码如下
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; namespace MyWindowsService { public partial class Service1 : ServiceBase { private System.Threading.Timer timer; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimerProc)); // 计时器将在1秒后执行,每隔5秒执行一次 timer.Change(1000, 5000); } protected override void OnStop() { } private void TimerProc(object state) { // do something } } }
计时器的设定一般做法是服务项目中创建一个配置文件App.Config,通过读取配置文件来设定计时器的执行间隔等执行策略。
好了,到了这里,我们的windows服务开发已经完成了,下面是创建安装包。
在Service1.cs的设计页面中右键选择添加安装程序
系统又会帮着生成ProjectInstall.cs文件,文件中两个控件属性需要设置一下。注意serviceProcessInstaller1的Account属性,设置成LocalSystem
接下来,要在解决方案中添加一个新的安装项目
右键点击项目MyServiceSetup1,在视图里选择自定义操作。得到以下视图
右键安装,选择添加自定义操作,在应用程序文件夹里添加输出
选择主输出后确定,继续确定后会得到以下界面
也可以在卸载操作中添加同样内容,这样你的安装包就有了卸载功能。
后面要做的工作就是编译生成安装包,然后安装即可。
安装完毕后查看本地服务列表可以看到
启动服务后就可以干活了!
因为是windows服务,所以代码必须做好容错处理,记文件日志是个不错的方法。