• Windows服务的创建、安装、卸载


    1.新建Window服务项目

    2.添加安装配置文件

    3.serviceProcessInstaller1右键属性,设置Account属性为LocalSystem。

    serviceInstaller1右键属性,设置Description、DisplayName、StartType。

    这些设置在安装后的服务中可以看到。

    cmd下输入services.msc,可以看到系统的服务。

    Description为服务中显示的描述信息。

    DisplayName为服务名称

    StartType启动类型,常用的有手动(Manual)、自动(Automatic)。

    设置好后,点击保存。

    4.编写服务执行的代码

    双击Services1.cs,右键查看代码。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    
    namespace WindowsService1
    {
        public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {
            }
    
            protected override void OnStop()
            {
            }
        }
    }


    显示了服务开始事件、停止事件。

    我们如果要实现定时任务的话,可以在构造方法中使用Timer

    public Service1()
            {
                InitializeComponent();
    
                Timer timer = new Timer();
                timer.Interval = 60 * 1000 * AppHelper.Interval;
                timer.Enabled = true;
                timer.Elapsed += TimedEvent;
            }
     private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
            {
            }

    5.至此一个服务创建完成,下来介绍服务的安装。
    找到服务项目bin/debug下的文件,CopyD:WindowsService下。

    当然这个路径是任意的,执行安装任务、卸载任务的时候需要使用。

    C:WindowsMicrosoft.NETFramework64v4.0.30319下找到InstallUtil.exe这个文件。

    因为我用的64位的系统,32位前往C:WindowsMicrosoft.NETFrameworkv4.0.30319中找这个文件。

    将这个安装、卸载文件Copy到D:WindowsService下。

    所有准备工作做好了,下来说安装。

    管理员身份运行cmd,之后执行D:WindowsServiceInstallUtil.exe D:WindowsServiceWindowsService1.exe 回车

    cmd下输入services.msc根据名称就可以看到我们安装的服务了。

    服务安装好运行起来后,我们想要用vs调试下服务代码怎么操作了?

    选择vs上的debug(调试)-》附加到进程-》勾选显示所有用户的进程,这个时候就能看到我们安装的进程了,选择这个进程。

    对于定时任务,定时器执行的事件处设置好断点,等到定时器间隔到时,就会看到程序走到断点处了。

    6.服务卸载

    管理员身份运行cmd,之后执行D:WindowsServiceInstallUtil.exe -u D:WindowsServiceWindowsService1.exe 回车

  • 相关阅读:
    npm启动报错Module not found: Error: Can't resolve 'fs'
    微信小程序
    window.URL对象的使用方式
    flex属性取值
    bindtap方法传参
    centos7安全相关设置
    签名证书
    gitlabci && runner use docker
    sftp 多用户,多目录不同权限设置
    grpc中TLS认证证书问题
  • 原文地址:https://www.cnblogs.com/tanpeng/p/6371154.html
Copyright © 2020-2023  润新知