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