(轉)建立Windows服務(Windows Services)N種方式總結

轉自:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.htmlhtml

最近因爲工做須要,寫了一些windows服務程序,有一些經驗,我如今總結寫出來。
目前我知道的建立建立Windows服務有3種方式:
a.利用.net框架類ServiceBase
b.利用組件Topshelf
c.利用小工具instsrv和srvanywindows

下面我利用這3種方式,分別作一個windows服務程序,程序功能就是每隔5秒往程序目錄下記錄日誌:框架

 

a.利用.net框架類ServiceBase編輯器

本方式特色:簡單,兼容性好ide

經過繼承.net框架類ServiceBase實現工具

第1步: 新建一個Windows服務網站

複製代碼
    public partial class Service1 : ServiceBase
    {
        readonly Timer _timer;

        private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @"\" + "test.txt";

        public Service1 ( )
        {
            InitializeComponent ( );

            _timer = new Timer ( 5000 )
            {
                AutoReset = true ,
                Enabled = true
            };

            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }

        protected override void OnStart ( string [ ] args )
        {
            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
        }

        protected override void OnStop ( )
        {
            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
        }

        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }

    }
複製代碼

第2步: 添加Installerthis

複製代碼
    [RunInstaller ( true )]
    public partial class Installer1 : System.Configuration.Install.Installer
    {
        private ServiceInstaller serviceInstaller;
        private ServiceProcessInstaller processInstaller;

        public Installer1 ( )
        {
            InitializeComponent ( );

            processInstaller = new ServiceProcessInstaller ( );
            serviceInstaller = new ServiceInstaller ( );

            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            serviceInstaller.ServiceName = "my_WindowsService";
            serviceInstaller.Description = "WindowsService_Description";
            serviceInstaller.DisplayName = "WindowsService_DisplayName";

            Installers.Add ( serviceInstaller );
            Installers.Add ( processInstaller );
        }  
    }
複製代碼

第3步:安裝,卸載 
Cmd命令
installutil      WindowsService_test.exe  (安裝Windows服務)
installutil /u   WindowsService_test.exe  (卸載Windows服務)spa

代碼下載:http://files.cnblogs.com/aierong/WindowsService_test.rar.net

 

b.利用組件Topshelf

本方式特色:代碼簡單,開源組件,Windows服務可運行多個實例

Topshelf是一個開源的跨平臺的服務框架,支持Windows和Mono,只須要幾行代碼就能夠構建一個很方便使用的服務. 官方網站:http://topshelf-project.com

 

第1步:引用程序集TopShelf.dll和log4net.dll

第2步:建立一個服務類MyClass,裏面包含兩個方法Start和Stop,還包含一個定時器Timer,每隔5秒往文本文件中寫入字符

複製代碼
    public class MyClass
    {
        readonly Timer _timer;

        private static readonly string FileName = Directory.GetCurrentDirectory ( ) + @"\" + "test.txt";

        public MyClass ( )
        {
            _timer = new Timer ( 5000 )
            {
                AutoReset = true ,
                Enabled = true
            };

            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }

        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }

        public void Start ( )
        {
            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
        }

        public void Stop ( )
        {
            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
        }

    }
複製代碼

第3步:使用Topshelf宿主咱們的服務,主要是Topshelf如何設置咱們的服務的配置和啓動和中止的時候的方法調用

複製代碼
    class Program
    {
        static void Main ( string [ ] args )
        {
            HostFactory.Run ( x =>
            {
                x.Service<MyClass> ( ( s ) =>
                {
                    s.SetServiceName ( "ser" );
                    s.ConstructUsing ( name => new MyClass ( ) );
                    s.WhenStarted ( ( t ) => t.Start ( ) );
                    s.WhenStopped ( ( t ) => t.Stop ( ) );
                } );

                x.RunAsLocalSystem ( );

                //服務的描述
                x.SetDescription ( "Topshelf_Description" );
                //服務的顯示名稱
                x.SetDisplayName ( "Topshelf_DisplayName" );
                //服務名稱
                x.SetServiceName ( "Topshelf_ServiceName" );

            } );
        }
    }
複製代碼

第4步: cmd命令

ConsoleApp_Topshelf.exe  install    (安裝Windows服務)

ConsoleApp_Topshelf.exe  uninstall  (卸載Windows服務)

 

代碼下載:http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar

 

c.利用小工具instsrv和srvany

本方式特色:代碼超級簡單,WindowsForm程序便可,並支持程序交互(本人最喜歡的特色),好像不支持win7,支持xp win2003

首先介紹2個小工具:

instsrv.exe:用以安裝和卸載可執行的服務

srvany.exe:用於將任何EXE程序做爲Windows服務運行

 

這2個工具都是是Microsoft Windows Resource Kits工具集的實用的小工具 

你能夠經過下載並安裝Microsoft Windows Resource Kits得到 http://www.microsoft.com/en-us/download/details.aspx?id=17657

 

第1步: 新建WindowsForm程序

複製代碼
   public partial class Form1 : Form
    {
        Timer _timer;

        private static readonly string FileName = Application.StartupPath + @"\" + "test.txt";

        public Form1 ( )
        {
            InitializeComponent ( );
        }

        private void Form1_Load ( object sender , EventArgs e )
        {
            _timer = new Timer ( )
            {
                Enabled = true ,
                Interval = 5000
            };

            _timer.Tick += delegate ( object _sender , EventArgs _e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }

        void _timer_Tick ( object sender , EventArgs e )
        {
            throw new NotImplementedException ( );
        }

        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }

        private void button1_Click ( object sender , EventArgs e )
        {
            MessageBox.Show ( "Hello" );
        }

    }
複製代碼

 

 

第2步:安裝,卸載

服務的安裝步驟分5小步:

(1)打開CMD,輸入如下內容,其中WindowsForms_WindowsService爲你要建立的服務名稱

格式:目錄絕對路徑\instsrv  WindowsForms_WindowsService  目錄絕對路徑\srvany.exe

例如:

D:\TempWork\win\Debug\instsrv.exe  WindowsForms_WindowsService  D:\TempWork\win\Debug\srvany.exe

 

(2)regedit打開註冊表編輯器,找到如下目錄

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WindowsForms_WindowsService

 

(3)鼠標右鍵單擊WindowsForms_WindowsService,建立一個"項",名稱爲"Parameters"

 

(4)鼠標左鍵單擊"Parameters",在右邊點擊鼠標右鍵,建立一個"字符串值"(REG_SZ),名稱爲"Application",數值數據裏填寫目錄下可執行文件的絕對路徑+文件名

例如:

D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe

 

(5)打開services.msc服務控制面板,找到WindowsForms_WindowsService服務,鼠標右鍵-屬性-登錄,勾選"容許服務與桌面交互"

 

啓動服務,能夠看到程序界面

 


 

卸載服務

D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService REMOVE

 

代碼下載:http://files.cnblogs.com/aierong/WindowsFormsApplication_Exe.rar

相關文章
相關標籤/搜索