C#创建windows服务并定时执行
一、創(chuàng)建window服務(wù)
1、新建項目-->選擇Windows服務(wù)。默認(rèn)生成文件包括Program.cs,Service1.cs
2、在Service1.cs添加如下代碼:
?? ? ? System.Timers.Timer timer1; ?//計時器
?? ? ? ?public Service1()
?? ? ? ?{
?? ? ? ? ? ?InitializeComponent();
?? ? ? ?}
?? ? ? ?protected override void OnStart(string[] args) ?//服務(wù)啟動執(zhí)行
?? ? ? ?{
?? ? ? ? ? ?timer1 = new System.Timers.Timer();
?? ? ? ? ? ?timer1.Interval = 3000; ?//設(shè)置計時器事件間隔執(zhí)行時間
?? ? ? ? ? ?timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
?? ? ? ? ? ?timer1.Enabled = true;
?? ? ? ?}
?? ? ? ?protected override void OnStop() ?//服務(wù)停止執(zhí)行
?? ? ? ?{
?? ? ? ? ? ?this.timer1.Enabled = false;
?? ? ? ?}
?
?? ? ? ?private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
?? ? ? ?{
?? ? ? ? ? ?//執(zhí)行SQL語句或其他操作
?? ? ? ?}
?
二、添加window服務(wù)安裝程序
1、打開Service1.cs【設(shè)計】頁面,點擊右鍵,選擇【添加安裝程序】,會出現(xiàn)serviceInstaller1和serviceProcessInstaller1兩個組件
2、將serviceProcessInstaller1的Account屬性設(shè)為【LocalSystem】, serviceInstaller1的StartType屬性設(shè)為【Automatic】,ServiceName屬性可設(shè)置服務(wù)名稱,此后在【管理工 具】--》【服務(wù)】中即顯示此名稱
3、ProjectInstaller.cs文件,在安裝服務(wù)后一般還需手動啟動(即使上述StartType屬性設(shè)為【Automatic】),可在ProjectInstaller.cs添加如下代碼實現(xiàn)安裝后自動啟動
?? ?public ProjectInstaller()
?? ? ? ?{
?? ? ? ? ? ?InitializeComponent();
?? ? ? ? ? ?this.Committed += new InstallEventHandler(ProjectInstaller_Committed); ??
?? ? ? ?}
?
?? ? ? ?private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
?? ? ? ?{
?? ? ? ? ? ?//參數(shù)為服務(wù)的名字
?? ? ? ? ? ?System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("服務(wù)名稱");
?? ? ? ? ? ?controller.Start();
?? ? ? ?} ??
?
三、安裝、卸載window服務(wù)
1、輸入cmd(命令行),輸入cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319,2.0為cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
2、安裝服務(wù)(項目生成的exe文件路徑)
??InstallUtil "E:\WindowsService1\bin\Debug\WindowsService1.exe"
3、卸載服務(wù)
??InstallUtil ?/u "E:\WindowsService1\bin\Debug\WindowsService1.exe"
四、查看window服務(wù)
控制面板-->管理工具-->服務(wù),可在此手動啟動,停止服務(wù)
五、調(diào)試window服務(wù)
1、通過【事件查看器】查看
2、直接在程序中調(diào)試(菜單-->調(diào)試-->附加進程-->服務(wù)名(這里的服務(wù)名是項目名稱,不是ServiceName屬性自定義的名稱,所以建議自定義名稱和項目名稱保持一致,另外需勾選【顯示所有用戶的進程】才能看到服務(wù)名)-->附加
3. 在程序中打斷點調(diào)試即可,另外調(diào)試服務(wù)時服務(wù)必須已啟動(管理工具-->服務(wù))
?
?
文字轉(zhuǎn)自:http://blog.csdn.net/armyfai/article/details/8056976
?
?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Threading;
namespace InnPoint
{
??? public partial class Service : ServiceBase
??? {
??????? public Service()
??????? {
??????????? InitializeComponent();
??????? }
??????? protected override void OnStart(string[] args)
??????? {
??????????? EventLog.WriteEntry("我的服務(wù)啟動");//在系統(tǒng)事件查看器里的應(yīng)用程序事件里來源的描述
??????????? writestr("服務(wù)啟動");//自定義文本日志
??????????? System.Timers.Timer t = new System.Timers.Timer();
??????????? t.Interval = 1000;
??????????? t.Elapsed += new System.Timers.ElapsedEventHandler(ChkSrv);//到達時間的時候執(zhí)行事件;?
??????????? t.AutoReset = true;//設(shè)置是執(zhí)行一次(false)還是一直執(zhí)行(true);?
??????????? t.Enabled = true;//是否執(zhí)行System.Timers.Timer.Elapsed事件;?
??????? }
??????? /// <summary>
??????? /// 定時檢查,并執(zhí)行方法
??????? /// </summary>
??????? /// <param name="source"></param>
??????? /// <param name="e"></param>
??????? public void ChkSrv(object source, System.Timers.ElapsedEventArgs e)
??????? {
??????????? int intHour = e.SignalTime.Hour;
??????????? int intMinute = e.SignalTime.Minute;
??????????? int intSecond = e.SignalTime.Second;
???????????
??????????? if (intHour == 13 && intMinute == 30 && intSecond == 00) ///定時設(shè)置,判斷分時秒
??????????? {
??????????????? try
??????????????? {
??????????????????? System.Timers.Timer tt = (System.Timers.Timer)source;
??????????????????? tt.Enabled = false;
??????????????????? SetInnPoint();
??????????????????? tt.Enabled = true;
??????????????? }
??????????????? catch (Exception err)
??????????????? {
??????????????????? writestr(err.Message);
??????????????? }
??????????? }
??????? }
??????? //我的方法
??????? public void SetInnPoint()
??????? {
??????????? try
??????????? {
??????????????? writestr("服務(wù)運行");
??????????????? //這里執(zhí)行你的東西
?????? Thread.Sleep(10000);
??????????? }
??????????? catch (Exception err)
??????????? {
??????????????? writestr(err.Message);
??????????? }
??????? }
??????? ///在指定時間過后執(zhí)行指定的表達式
??????? ///
??????? ///事件之間經(jīng)過的時間(以毫秒為單位)
??????? ///要執(zhí)行的表達式
??????? public static void SetTimeout(double interval, Action action)
??????? {
??????????? System.Timers.Timer timer = new System.Timers.Timer(interval);
??????????? timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
??????????? {
??????????????? timer.Enabled = false;
??????????????? action();
??????????? };
??????????? timer.Enabled = true;
??????? }
?
??????? public void writestr(string readme)
??????? {
??????????? //debug==================================================
??????????? //StreamWriter dout = new StreamWriter(@"c:\" + System.DateTime.Now.ToString("yyyMMddHHmmss") + ".txt");
??????????? StreamWriter dout = new StreamWriter(@"c:\" + "WServ_InnPointLog.txt", true);
??????????? dout.Write("\r\n事件:" + readme + "\r\n操作時間:" + System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
??????????? //debug==================================================
??????????? dout.Close();
??????? }
??????? protected override void OnStop()
??????? {
??????????? writestr("服務(wù)停止");
??????????? EventLog.WriteEntry("我的服務(wù)停止");
??????? }
??? }
}
3.在Service1.cs設(shè)計頁面右鍵添加安裝程序
4.ProjectInstaller.cs設(shè)計頁面中
??? serviceInstaller1屬性中設(shè)置:
??? Description(系統(tǒng)服務(wù)的描述)
??? DisplayName (系統(tǒng)服務(wù)中顯示的名稱)
??? ServiceName(系統(tǒng)事件查看器里的應(yīng)用程序事件中來源名稱)
??? serviceProcessInstaller1屬性設(shè)置:Account 下拉設(shè)置成 LocalSystem
5.在.net Framework的安裝目錄可以找到InstallUtil.exe,可以復(fù)制出來放在你的服務(wù)生成的exe一起
6.安裝服務(wù)setup.bat批處理文件內(nèi)容:InstallUtil Service1.exe ,安裝好后可以在系統(tǒng)服務(wù)中找到你設(shè)置的服務(wù)名稱然后可以啟動這個服務(wù)
7.卸載服務(wù)UnInstall.bat批處理文件內(nèi)容:InstallUtil -u Service1.exe
總結(jié)
以上是生活随笔為你收集整理的C#创建windows服务并定时执行的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 针对OAuth2的CSRF攻击
- 下一篇: 阿里云支撑马来西亚数字自由贸易区落地 帮