一、前言
开发中经常会遇到需要在某个特定时间(定时),去处理某些事情的业务需求。通常 。常用的有 Timer 和 是一个Java开源的作业调度框架,后面才移植到 平台上面,在配置文件中简单配置就可以实现作业调度功能。而 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;
request =
System.IO.Stream requestStream = default(System.IO.Stream);
byte[] postBytes = null;
string url =
request =
request.ContentType =
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
设置 Account3.设置 服务名称(根据自己需求)
设置服务名称4.生成项目,在 ~/bin/debug/ 中找到我们的服务可执行文件 “项目名.exe”
生成项目5.安装服务的命令
1.管理员权限运行命令行工具
cd
cd
2.安装服务。注意后面的路径就是我们可执行文件的存放路径
InstallUtil "D:\ZDFService.exe"
6.安装成功
安装成功7.启动服务
启动服务8.卸载
InstallUtil /u "D:\ZDFService.exe"