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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?