一、前言
开发中经常会遇到需要在某个特定时间(定时),去处理某些事情的业务需求。通常 .NET在遇到这个问题的时候可以采用定时器的方式来解决这个问题。常用的有 Timer 和 Quartz.Net(第三方组件),Quartz.NET 是一个Java开源的作业调度框架,后面才移植到 .NET 平台上面,在配置文件中简单配置就可以实现作业调度功能。而 Timer 的使用更加简单,如果是在项目中的话,直接在 Application_Start 调用即可。今天我们这两种种方式都不做介绍。我们来研究一下作为系统服务运行的作业调度。
二、WindowsServer
顾名思义,在 Windows 系统下的服务。如下图:
下面我们来看看怎样开发 WindowsService
1.WindowsService 创建项目
2.右键查看代码 或者 F7
3.添加代码
创建 Timer 对象
System.Timers.Timer time;
设置定时器属性
protected override void OnStart(string[] args)
{
time = new System.Timers.Timer();
EventLog.WriteEntry("***我是描述****");
time.Interval = 1000 * 60 * 60;//执行间隔....每小时执行
time.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
time.Elapsed += new System.Timers.ElapsedEventHandler(MyEvent);//利用委托执行方法
time.Enabled = true;//开启定时器
}
结束关闭定时器
protected override void OnStop()
{
this.time.Enabled = false;
}
4.业务代码,笔者是需要自动掉某个API,代码如下,仅供参考
public void MyEvent(object sender, System.Timers.ElapsedEventArgs e)
{
string postData = string.Empty;
System.Net.HttpWebRequest request = default(System.Net.HttpWebRequest);
System.IO.Stream requestStream = default(System.IO.Stream);
byte[] postBytes = null;
string url = "http://yoururl.com";//api
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.Timeout = 10000;
request.Method = "POST";
request.AllowAutoRedirect = false;
requestStream = request.GetRequestStream();
postBytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
注意实际应用上要进行验证,API是否为合法调用
三、WindowsService 的发布和安装
1.添加安装程序
2.设置 Account
3.设置 服务名称(根据自己需求)
4.生成项目,在 ~/bin/debug/ 中找到我们的服务可执行文件 “项目名.exe”
5.安装服务的命令
1.管理员权限运行命令行工具
cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
.net framework 2.0 为
cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
2.安装服务。注意后面的路径就是我们可执行文件的存放路径
InstallUtil "D:\ZDFService.exe"
6.安装成功
7.启动服务
8.卸载
InstallUtil /u "D:\ZDFService.exe"