建立一個windows服務(可用於實現計劃任務,事件監控..) .NET

來源:互聯網
上載者:User

什麼是windows服務?

一個Windows服務程式是在Windows作業系統下能完成特定功能的可執行檔應用程式。Windows服務程式雖然是可執行檔,但是它不像一般的可執行檔通過雙擊就能開始運行了,它必須有特定的啟動方式。這些啟動方式包括了自動啟動和手動啟動兩種。對於自動啟動的Windows服務程式,它們在 Windows啟動或是重啟之後使用者登入之前就開始執行了。只要你將相應的Windows服務程式註冊到服務控制管理員(Service Control Manager)中,並將其啟動類別設為自動啟動就行了。而對於手動啟動的Windows服務程式,你可以通過命令列工具的NET START 命令來啟動它,或是通過控制台中管理工具下的服務一項來啟動相應的Windows服務程式(見圖1)。同樣,一個Windows服務程式也不能像一般的應用程式那樣被終止。因為Windows服務程式一般是沒有使用者介面的,所以你也要通過命令列工具或是下面圖中的工具來停止它,或是在系統關閉時使得 Windows服務程式自動停止。因為Windows服務程式沒有使用者介面,所以基於使用者介面的API函數對其是沒有多大的意義。為了能使一個 Windows服務程式能夠正常並有效在系統內容下工作,程式員必須實現一系列的方法來完成其服務功能。Windows服務程式的應用範圍很廣,典型的 Windows服務程式包含了硬體控制、應用程式監視、系統級應用、診斷、報告、Web和檔案系統服務等功能。

通過時間控制項 定時檢測實現執行任務的

自動會在相應的工程(如WinService1)中建立一個Service1.cs的檔案(將Service1.cs改名為ScheduleService.cs),選中該檔案,查看代碼,

using System;
using System.ServiceProcess;
using System.Timers;

namespace WinService1
{
public partial class ScheduleService : ServiceBase
{
#region 屬性定義

/// <summary>
/// 定時器
/// </summary>
Timer Timer1;

#endregion

public ScheduleService()
{
InitializeComponent();
Timer1 = new Timer();
ServiceName = "ScheduleService";
CanStop = true;
CanShutdown = true;
CanPauseAndContinue = true;
AutoLog = true;

Timer1.Elapsed += Timer1_Elapsed;
Timer1.Interval = 1000;
Timer1.Start();
}

/// <summary>
/// 達到間隔時間
/// </summary>
void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
if (e.SignalTime.Second == 0)//每分鐘執行一次
{
//檢測設定檔中,是否有需要執行的任務


if (false)
{
WriteLog("檔案1", "已經檢測過了,有要執行的任務:***,並已安排執行");
}
else
WriteLog("檔案1", "已經檢測過了,沒有要執行的任務");
}
}

protected override void OnStart(string[] args)
{
base.OnStart(args);
WriteLog("檔案1", "WinService1.OnStart" + " 服務啟動");
}

protected override void OnStop()
{
base.OnStop();
WriteLog("檔案1", "WinService1.OnStop" + " 服務停止");
}

#region Log

private static string logPath = string.Empty;
/// <summary>
/// 儲存日誌的檔案夾
/// </summary>
public static string LogPath
{
get
{
if (logPath == string.Empty)
{
if (System.Web.HttpContext.Current == null)
// Windows Forms 應用
logPath = AppDomain.CurrentDomain.BaseDirectory;
else
// Web 應用程式
logPath = AppDomain.CurrentDomain.BaseDirectory + @"bin";
}
return logPath;
}
set { logPath = value; }
}

/// <summary>
/// 寫日誌
/// </summary>
/// <param name="logFile">檔案名稱,如:Info</param>
/// <param name="msg">日誌內容</param>
public static void WriteLog(string logFile, string msg)
{
try
{
System.IO.StreamWriter sw = System.IO.File.AppendText(
LogPath + logFile + " " +
DateTime.Now.ToString("yyyyMMdd") + ".Log"
);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg);
sw.Close();
}
catch
{ }
}

#endregion

}
}

 

建立類MyInstaller.cs

using System;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;
namespace WinService1
{
[RunInstaller(true)]
public partial class MyInstaller : Installer
{
private ServiceInstaller sInstall;
private ServiceProcessInstaller sProcessInstall;
public MyInstaller()
{
sInstall = new ServiceInstaller();
sProcessInstall = new ServiceProcessInstaller();
sProcessInstall.Account = ServiceAccount.LocalSystem;
sInstall.StartType = ServiceStartMode.Automatic;
sInstall.ServiceName = "ScheduleService"; //這個服務名必須和步驟1中的服務名相同。
sInstall.DisplayName = "任務計劃 服務";
sInstall.Description = "這是該任務計劃服務的描述..";
Installers.Add(sInstall);
Installers.Add(sProcessInstall);
}
}
}

 

在Program.cs中

using System.ServiceProcess;

namespace WinService1
{
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ScheduleService()
};
ServiceBase.Run(ServicesToRun);

//在運行中,將目前的目錄轉向WinService1.exe所在的目錄,(盤符直接切換, cd 切換檔案夾)
//然後輸入 F:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe WinService1.exe
//則在服務中可以看到新增了一項服務

//另外,刪除服務的方法如下:
//在運行中,將目前的目錄轉向WinService1.exe所在的目錄,
//sc delete myservice (myservice為當前要刪除的服務名),即可刪除該服務
}
}
}

產生一下該工程,然後

根據Program.cs中的相關注釋,在 管理>服務中添加上 新的服務,然後啟動;

在調試>附加到進程 中

此時即可調試服務程式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.