3.AddInstaller(添加安装程序)
StartType共有五种类型:Boot(开机启动)、Automatic(自动)、System(系统)、Manual(手动)、Disabled(禁用)
Account共有五种:LocalSystem(本地系统)、LocalService(本地服务)、NetworkService(网络服务)、User(用户)
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(); } } } }
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
以管理员身份运行intsall.bat
查看日志
执行uninsatll.bat
Quartz.Net系列(十一):System.Timers.Timer+WindowsService实现定时任务
原文:https://www.cnblogs.com/vic-tory/p/13280155.html