Quartz.Net系列(十一):System.Timers.Timer+WindowsService實現定時任務
阿新 • • 發佈:2020-07-10
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(); //_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