Quartz.Net系列(十一):System.Timers.Timer+WindowsService实现定时任务
1.创建WindowsService项目
2.配置项目
3.AddInstaller(添加安装程序)
4.修改ServiceName(服务名称)、StartType(启动类型)、Description(说明)、DisplayName(显示名称)
StartType共有五种类型:Boot(开机启动)、Automatic(自动)、System(系统)、Manual(手动)、Disabled(禁用)
5.选择Account:LocalSystem
Account共有五种:LocalSystem(本地系统)、LocalService(本地服务)、NetworkService(网络服务)、User(用户)
6.编写Timer触发器
using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace WindowsService_Demo { public partial class WindowServiceDemo : ServiceBase { private System.Timers.Timer _timer=null; public WindowServiceDemo() { InitializeComponent(); } /// <summary> /// 服务启动 /// </summary> /// <param name="args"></param> protected override void OnStart(string[] args) { //实例化定时器 并设置间隔为1秒 _timer = new System.Timers.Timer(6000); //_timer.Interval = 6000; 设置间隔为1秒 _timer.Start(); //_timer.Enabled=true; WriteText("定时服务开始了"); _timer.Elapsed += Timer_Elapsed; } private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { WriteText("定时服务正在执行"); } /// <summary> /// 服务停止 /// </summary> protected override void OnStop() { _timer?.Close(); WriteText("定时服务停止了"); } private static void WriteText(string message) { string path = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; string fullPath = path + "log.txt"; StreamWriter streamWriter=null; try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!File.Exists(fullPath)) { streamWriter = File.CreateText(fullPath); } else { streamWriter = File.AppendText(fullPath); } streamWriter.WriteLine(message +"----------------------"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } finally { streamWriter?.Close(); } } } }
7.新建install.bat和uninstall.bat文件(dos下的批处理文件) pause(表示按任意键结束)
install.bat
c: cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319 InstallUtil.exe -i F:\project\dotnet\WindowsService-Demo\WindowsService-Demo\bin\Debug\WindowsService-Demo.exe net start WindowServiceDemo sc config WindowServiceDemo start=auto pause
uninstall.bat
c: cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319 InstallUtil.exe -i F:\project\dotnet\WindowsService-Demo\WindowsService-Demo\bin\Debug\WindowsService-Demo.exe net start WindowServiceDemo sc config WindowServiceDemo start=auto pause
8.运行(必须以超级管理员身份)
以管理员身份运行intsall.bat
查看日志
9.停止Window服务(必须以超级管理员身份)
执行uninsatll.bat
微信:17873041739