在ASP.NET中建立计划任务,就我我的而言,用过两种方式,一种是用SQL Server建立,把写好的SSIS包导入SQL Server建立的任务中,设置好时间让它去执行。还有一种就是利用window 服务。接下来我将讲述如何用window service 去建立计划任务,让它在咱们设定的时间内执行。git
1.新建项目,而后选择Windows服务。以下:github
2.右键空白处,选择“添加安装程序”。ide
3.右键 serviceProcessInstaller1,选择属性,将Account的值改成LocalSystem。目的是为了保证不管哪一个用户使用这台电脑都能启动服务。工具
4.打开 Service1.cs设计界面,从工具箱里面拖一个timer控件进来,检查咱们的程序是否到了执行时间了。spa
5.右键timer,选择属性,切换到事件,给timer控件绑定一个tick事件.设计
6.添加一个 Scheduler.cs(本身命名) 里面写入咱们须要执行的逻辑代码。对于做业一般会须要设置执行时间,执行的周期,好比星期一到星期五,哪几天执行,几点钟执行等。咱们能够创建相关表,存储设置的执行时间和周期,而后在代码里去判断时间是否符合,若是符合就继续执行。固然在这里我为了举例方便,就只写一个很简单的方法。3d
namespace WindowsServiceDemo { class Scheduler { static void Record() { using (System.IO.StreamWriter sw = new System.IO.StreamWriter("E:\\log.txt", true)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ")); } } } }
7.在Service1.cs里面去调用 code
namespace WindowsServiceDemo { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer1.Enabled = true; timer1.Start(); timer1_Tick(timer1, null); } protected override void OnStop() { timer1.Stop(); } private void timer1_Tick(object sender, EventArgs e) { Scheduler.Record(); } } }
8.安装window 服务blog
1)安装脚本Install.bat事件
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceDemo.exe Net Start Service1 sc config Service1 start= auto
2)卸载脚本Uninstall.bat
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceDemo.exe
把这两个脚本和最后生成的做业放在同一目录,而后运行Install.bat。这时,咱们打开服务管理界面,能够看到咱们安装的服务。
而后再打开E盘,能够看到record方法执行成功。
代码下载:https://github.com/Aulanto/window-service-scheduler.git