一、前言
开发中经常会遇到需要在某个特定时间(定时),去处理某些事情的业务需求。通常 .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"
限于笔者技术,文章观点难免有不当之处,希望发现问题的朋友帮忙指正,笔者将会及时更新。也请转载的朋友注明文章出处并附上原文链接,以便读者能及时获取到文章更新后的内容,以免误导读者。笔者力求避免写些晦涩难懂的文章(虽然也有人说这样显得高逼格,专业),尽量使用简单的用词和例子来帮助理解。如果表达上有好的建议的话也希望朋友们在评论处指出。
本文为作者原创,转载请注明出处! 东野文然
网友评论