C#创建Windows服务(Windows Services) 实战之系统定时重启服务

来源:互联网 发布:淘宝如何申请信用卡 编辑:程序博客网 时间:2024/05/02 01:12
 //服务器重启服务,作者:柳永法 www.yongfa365.com
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;


namespace CBDCN_reboot
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            double sleeptime = ValidatorDate1(System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"), System.DateTime.Now.ToString("yyy-MM-dd ") + "07:00:00");
            if (sleeptime < 0) sleeptime += 24 * 60 * 60 * 1000;
            writestr("开始",sleeptime);
            System.Timers.Timer t = new System.Timers.Timer(sleeptime);//实例化Timer类,设置间隔时间为10000毫秒; 
            t.Elapsed += new System.Timers.ElapsedEventHandler(rebootsystem);//到达时间的时候执行事件; 
            t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); 
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件; 
            writestr("结束", sleeptime);
        }
        public void rebootsystem(object source, System.Timers.ElapsedEventArgs e)
        {
            System.Diagnostics.Process.Start("shutdown", "/r /f /t 0");
        }

        public static double ValidatorDate1(string strDateA, string strDateB)
        {
            string strFrom = strDateB;
            string strTo = strDateA;
            TimeSpan ts = Convert.ToDateTime(strFrom) - Convert.ToDateTime(strTo);
            double count = ts.TotalSeconds * 1000;
            return count;
        }


        public void writestr(string readme,double sleeptime)
        {
            //debug==================================================
            StreamWriter dout = new StreamWriter(@"c:\" + System.DateTime.Now.ToString("yyyMMddHHmmss") + readme + ".txt");
            dout.Write("\nSleepTime:" + Convert.ToString(sleeptime) + "\n操作时间:" + System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
            //debug==================================================
            dout.Close();
        } 

        protected override void OnStop()
        {

        }
    }

}

  1. 用C#创建Windows服务(Windows Services)  
  2.   
  3. Windows服务在Visual Studio 以前的版本中叫NT服务,在VS.net启用了新的名称。用Visual C# 创建Windows服务不是一件困难的事,本文就将指导你一步一步创建一个Windows服务并使用它。这个服务在启动和停止时,向一个文本文件中写入一些文字信息。  
  4.   
  5.  第一步:创建服务框架   
  6. 要创建一个新的 Windows 服务,可以从Visual C# 工程中选取 Windows 服务(Windows Service)选项,给工程一个新文件名,然后点击 确定。  
  7.   
  8. 你可以看到,向导向工程文件中增加WebService1.cs类:  
  9.   
  10. 其中各属性的含意是:  
  11.   
  12.         Autolog                 是否自动写入系统的日志文件  
  13.   
  14.         CanHandlePowerEvent     服务时候接受电源事件  
  15.   
  16.         CanPauseAndContinue          服务是否接受暂停或继续运行的请求  
  17.   
  18.         CanShutdown 服务是否在运行它的计算机关闭时收到通知,以便能够调用 OnShutDown 过程  
  19.   
  20.         CanStop                              服务是否接受停止运行的请求  
  21.   
  22.         ServiceName                       服务名  
  23.   
  24.    
  25.   
  26. 第二步:向服务中增加功能   
  27. 头部添加using System.IO;  
  28. 在 .cs代码文件中我们可以看到,有两个被忽略的函数 OnStart和OnStop。   
  29.   
  30. OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。在这里,当启动和停止服务时,向一个文本文件中写入一些文字信息,代码如下:  
  31.   
  32. protected override void OnStart(string[] args)  
  33. {  
  34.     // TODO: 在此处添加代码以启动服务。  
  35.     FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);  
  36.   
  37.     StreamWriter m_streamWriter = new StreamWriter(fs);  
  38.   
  39.     m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);  
  40.   
  41.     m_streamWriter.WriteLine("mcWindowsService:         Service Started" + DateTime.Now.ToString() + "\n");  
  42.   
  43.     m_streamWriter.Flush();  
  44.   
  45.     m_streamWriter.Close();  
  46.   
  47.     fs.Close();  
  48. }  
  49.   
  50. protected override void OnStop()  
  51. {  
  52.     // TODO: 在此处添加代码以执行停止服务所需的关闭操作。  
  53.     FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);  
  54.   
  55.     StreamWriter m_streamWriter = new StreamWriter(fs);  
  56.   
  57.     m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);  
  58.   
  59.     m_streamWriter.WriteLine(" mcWindowsService: Service Stopped " + DateTime.Now.ToString() + "\n");  
  60.   
  61.     m_streamWriter.Flush();  
  62.   
  63.     m_streamWriter.Close();  
  64.   
  65.     fs.Close();  
  66. }  
  67.   
  68.  第三步: 将安装程序添加到服务应用程序  
  69.   
  70.  Visual Studio.NET 随附有安装组件,可用来安装与服务应用程序相关联的资源。安装组件在正在安装到的系统上注册一项单个的服务,并使服务控制管理器知道该服务的存在。  
  71.   
  72. 要正确安装服务,并不需要在安装程序中进行任何特殊编码。但是,如果需要向安装进程添加特殊功能,则可能偶尔需要修改安装程序的内容。  
  73.   
  74.        将安装程序添加到服务应用程序的步骤是:  
  75.   
  76. 1:在解决方案中,访问要向其中添加安装组件的服务的Design视图。  
  77.   
  78. 2:在属性窗口中,单击"添加安装程序"链接,如果没有的话,您在属性下边的,灰色帮助区域右击,选中“命令”然后"添加安装程序"链接就出来了。  
  79.   
  80. 这时项目中就添加了一个新类 ProjectInstaller 和两个安装组件 ServiceProcessInstaller 和 ServiceInstaller,并且服务的属性值被复制到组件。   
  81.   
  82. 3:若要确定如何启动服务,请单击 ServiceInstaller 组件并将 StartType 属性设置为适当的值。  
  83.   
  84.          Manual      服务安装后,必须手动启动。  
  85.   
  86.          Automatic    每次计算机重新启动时,服务都会自动启动。  
  87.   
  88.          Disabled     服务无法启动。  
  89.   
  90. 4:将serviceProcessInstaller类的Account属性改为 LocalSystem  
  91.   
  92.      这样,不论是以哪个用户登录的系统,服务总会启动。  
  93.   
  94.    
  95.   
  96. 第四步:生成服务程序  
  97.   
  98. 通过从生成菜单中选择生成来生成项目。  
  99.   
  100. 注意   不要通过按 F5 键来运行项目——不能以这种方式运行服务项目。  
  101.   
  102. 第五步:安装服务  
  103.   
  104. 访问项目中的已编译可执行文件所在的目录。   
  105. 用项目的输出作为参数,从命令行运行 InstallUtil.exe。在命令行中输入下列代码:   
  106. installutil yourproject.exe  
  107.   
  108. 注:InstallUtil.exe有两个版,在我机器上的位置是:  
  109. C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\InstallUtil.exe     16K 用于.net1.1  
  110. C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe    26K 用于.net2.0  
  111.   
  112.   
  113. 卸载服务   
  114.   
  115. 用项目的输出作为参数,从命令行运行 InstallUtil.exe。   
  116.   
  117. installutil /u yourproject.exe  
  118.   
  119. 如果文件换了个文件夹,再运行可能会出错,您可以在CMD里输入:SC delete 服务名,删除这个服务

原创粉丝点击