使用Windows service建立一個簡單的定時器

1、需求

咱們有時候可能會想要作一些定時任務,例如每隔一段時間去訪問某個網站,或者下載一些東西到咱們服務器上等等之類的事情,這時候windows service 是一個不錯的選擇。windows

2、實現

一、打開Visua studio2013新建一個windows Service程序,我命名爲TimerService服務器

image

注意,這裏的.NET Framwork框架的選擇要與你電腦上的框架一致,我這裏選擇的是4.0框架

二、在Service1設計器中右擊空白處選擇查看代碼ide

image

3.在Service1.cs中設定定時的時間間隔以及定時執行的任務這裏的Onstart方法定義定時器的開始執行,執行的時間間隔,以及時間間隔達到後所要執行的方法,我這裏是執行了一個文件寫入的方法,代碼以下工具

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.Timers;

namespace TimerService
{
    public partial class Service1 : ServiceBase
    {
        Timer timer;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            timer.Start();
            WriteLog("服務啓動");
        }

        protected override void OnStop()
        {
            timer.Stop();
            timer.Dispose();
            WriteLog("服務中止");
        }

        protected void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            WriteLog("服務執行中");
        }

        protected void WriteLog(string str)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
            StreamWriter sw = null;
            if (!File.Exists(filePath))
            {
                sw = File.CreateText(filePath);
            }
            else
            {
                sw = File.AppendText(filePath);
            }
            sw.Write(str + DateTime.Now.ToString() + Environment.NewLine);
            sw.Close();
        }
    }
}

四、在Service1設計器中右擊空白處,選擇添加安裝程序,會添加一個ProjectInstaller設計器網站

image

五、在ProjectInstaller設計器中選擇serviceProcessInstaller,右擊查看屬性,將Account的值改成LocalSystemspa

image

六、在ProjectInstaller設計器中選擇serviceInstaller1,右擊查看屬性,這裏的ServiceName就是要在服務器的服務中顯示的名稱,我將其命名我TimerServicedebug

image

七、右擊解決方案,點擊生成解決方案設計

3、安裝

一、打開剛剛新建建項目所在的文件夾,找到bin文件下面的debug文件夾,即D:\用戶目錄\個人文檔\Visual Studio 2013\Projects\TimerService\TimerService\bin\Debug,裏面有個TimerService.exe應用程序,就是咱們所要執行的項目code

二、打開文件夾C:\Windows\Microsoft.NET\Framework\v4.0.30319,能夠看到裏面有一個InstallUtil.exe的應用程序,這就是咱們要的安裝工具,這裏的Framework的版本與咱們項目的Framework版本保持一致

三、打開cmd輸入cd C:\Windows\Microsoft.NET\Framework\v4.0.30319指令,而後再輸入InstallUtil D:\用戶目錄\個人文檔\Visual~1\Projects\TimerService\TimerService\bin\Debug\TimerService.exe,便可完成安裝

image

四、啓動任務管理器,點擊服務,找到名稱TemrService的服務,右擊啓動,便可將建立的定時服務啓動,這裏的服務名稱就是咱們在項目的serviceInstaller1的屬性裏面設置的serviceName

image

五、在咱們的D:\用戶目錄\個人文檔\Visual Studio 2013\Projects\TimerService\TimerService\bin\Debug文件下面會發現多了一個log.txt的文件,就是咱們在項目中建立的文件,打開便可看到項目正常執行

image

4、卸載

要卸載應用服務也很簡單,只須要在cmd中輸入如下指令便可

InstallUtil /u D:\用戶目錄\個人文檔\Visual~1\Projects\TimerService\TimerService\bin\Debug\TimerService.exe

image

相關文章
相關標籤/搜索