• .net手动编写Windows服务


    1,打开VS,新建一个windows服务程序。项目名称自定义,我这里用的默认名称:Service1

    2,打开Service1,按F7查看代码。代码里有三个方法:public Service1()、protected override void OnStart(string[] args)、protected override void OnStop(),

    分别是构造函数,服务启动方法,服务停止方法

    3,定义一个timer定时器,设置一段时间自动执行:

    System.Timers.Timer timer1;  //计时器

    timer1 = new System.Timers.Timer();
    timer1.Interval = 3000; //设置计时器事件间隔执行时间
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
    timer1.Enabled = true;

    4,编写服务具体执行的业务,这里是模拟的,就只写了一个txt文档,并且把写txt文档的方法放到了定时器的自动执行方法里

    /// <summary>
    /// 执行的事件
    /// </summary>
    /// <param name="obj"></param>
    private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        using (FileStream stream = new FileStream(filePath, FileMode.Append))
        using (StreamWriter writer = new StreamWriter(stream))
        {
            writer.WriteLine(DateTime.Now + ",自动服务的执行。。。");
        }
    }

    5,编译一下,无编译错误即可。完整的代码如下:

    public partial class Service1 : ServiceBase
    {
    System.Timers.Timer timer1; //计时器
    string filePath = @"D:MyServiceLog.txt";

    public Service1()
    {
    InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
    timer1 = new System.Timers.Timer();
    timer1.Interval = 3000; //设置计时器事件间隔执行时间
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
    timer1.Enabled = true;


    using (FileStream stream = new FileStream(filePath, FileMode.Append))
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.WriteLine(DateTime.Now + ",服务启动!");
    }
    }

    protected override void OnStop()
    {
    this.timer1.Enabled = false;

    using (FileStream stream = new FileStream(filePath, FileMode.Append))
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.WriteLine(DateTime.Now + ",服务停止!");
    }
    }


    /// <summary>
    /// 执行的事件
    /// </summary>
    /// <param name="obj"></param>
    private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
    using (FileStream stream = new FileStream(filePath, FileMode.Append))
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.WriteLine(DateTime.Now + ",自动服务的执行。。。");
    }
    }
    }

    6,在解决方案里双击Service.cs,打开设计器:

    在空白处右击,选择“添加安装程序”

     

    点击之后如下

    7,查看serviceInstaller1的属性,编辑它的描述信息和服务名称信息,如下:

    点击 serviceProcessInstaller1 ,编辑运行次服务的账户类型属性,设置成 LocalSystem,如下:

    8,服务配置完成,点击保存,重新生成。

    9,下面,我们写一个Windows窗体,用于安装、运行、停止、卸载这个服务:

    10,添加一个应用引用,把刚才写的服务引用到这个Windows窗体应用

    11,给每个按钮添加相应的代码,完整如下:

    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    string serviceFilePath = System.Environment.CurrentDirectory + "\WindowsService1.exe";
    string serviceName = "TestWindowsService";

    /// <summary>
    /// 安装服务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
    if (this.IsServiceExisted(serviceName))
    this.UninstallService(serviceName);
    this.InstallService(serviceFilePath);
    }
    /// <summary>
    /// 启动服务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
    if (this.IsServiceExisted(serviceName))
    this.ServiceStart(serviceName);
    }
    /// <summary>
    /// 停止服务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button3_Click(object sender, EventArgs e)
    {
    if (this.IsServiceExisted(serviceName))
    this.ServiceStop(serviceName);
    }
    /// <summary>
    /// 卸载服务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button4_Click(object sender, EventArgs e)
    {
    if (this.IsServiceExisted(serviceName))
    {
    this.ServiceStop(serviceName);
    this.UninstallService(serviceFilePath);
    }
    }


    //判断服务是否存在
    private bool IsServiceExisted(string serviceName)
    {
    ServiceController[] services = ServiceController.GetServices();
    foreach (ServiceController sc in services)
    {
    if (sc.ServiceName.ToLower() == serviceName.ToLower())
    {
    return true;
    }
    }
    return false;
    }

    //安装服务
    private void InstallService(string serviceFilePath)
    {
    using (AssemblyInstaller installer = new AssemblyInstaller())
    {
    installer.UseNewContext = true;
    installer.Path = serviceFilePath;
    IDictionary savedState = new Hashtable();
    installer.Install(savedState);
    installer.Commit(savedState);
    }
    }

    //卸载服务
    private void UninstallService(string serviceFilePath)
    {
    using (AssemblyInstaller installer = new AssemblyInstaller())
    {
    installer.UseNewContext = true;
    installer.Path = serviceFilePath;
    installer.Uninstall(null);
    }
    }
    //启动服务
    private void ServiceStart(string serviceName)
    {
    using (ServiceController control = new ServiceController(serviceName))
    {
    if (control.Status == ServiceControllerStatus.Stopped)
    {
    control.Start();
    }
    }
    }

    //停止服务
    private void ServiceStop(string serviceName)
    {
    using (ServiceController control = new ServiceController(serviceName))
    {
    if (control.Status == ServiceControllerStatus.Running)
    {
    control.Stop();
    }
    }
    }

    }

     12,编译,运行起来,点击安装服务。然后在计算机管理里,查看所有的服务,就可以找到刚才写的服务了:

  • 相关阅读:
    Attribute
    SQL Server 存储过程
    SQL语句:CRUD
    TCP模拟实现文本文件上传Java代码
    C# Attribute-特性
    Android Pull 读取XML
    【转】SVM入门(九~十一)松弛变量(续)
    【转】SVM入门(八)松弛变量
    【转】SVM入门(七)为何需要核函数
    【转】SVM入门(六)线性分类器的求解——问题的转化,直观角度
  • 原文地址:https://www.cnblogs.com/huyueping/p/9242485.html
Copyright © 2020-2023  润新知