zoukankan      html  css  js  c++  java
  • windows服务开发

    学然后知不足 教然后知困。

    没做过windows service开发时,感觉很难,无从下手。再网看了些例子,加上自己的理解,写下开发步骤。

    开发步骤

    1. 新建windows service

    2. 添加服务,发表后将再自己的电脑的 服务管理 查看到

    	partial class MyService : ServiceBase
    	{
    		Timer timer1;
    
    		public MyService()
    		{
    			InitializeComponent();
    		}
    
    		protected override void OnStart(string[] args)
    		{
    			// TODO: Add code here to start your service.
    
    			using (StreamWriter sw = File.AppendText(@"D:\log2.txt"))
    			{
    				sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Start.");
    			}
    
    			timer1 = new Timer();
    			timer1.Interval = 2000;
    			timer1.Elapsed += (sender, e) =>
    			{
    				using (StreamWriter sw = File.AppendText(@"D:\log2.txt"))
    				{
    					sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Countue...");
    				}
    			};
    			timer1.Start();
    		}
    
    		protected override void OnStop()
    		{
    			// TODO: Add code here to perform any tear-down necessary to stop your service.
    			using (StreamWriter sw = File.AppendText(@"D:\log2.txt"))
    			{
    				sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Stop.");
    			}
    		}
    	}
    
    1. 添加服务安装程序(这是vs给提供的方便操作),可以发表多个服务。

    右击,点击Add Installer,自动生成类ProjectInstaller。大家可以看下vs自动生成的类ProjectInstaller.Designer.cs文件

    private void InitializeComponent()
    		{
    			this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
    			this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
    			//设置服务安装信息
    			this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
    			this.serviceProcessInstaller1.Password = null;
    			this.serviceProcessInstaller1.Username = null;
    			//要安装的服务(保证与你的服务名一致,可添加多个)
    			this.serviceInstaller1.ServiceName = "MyService";
    			//服务加入
    			this.Installers.AddRange(new System.Configuration.Install.Installer[] {
                this.serviceProcessInstaller1,
                this.serviceInstaller1});
    
    		}
    

    注意将服务安装设置为:手动安装
    4. 服务安装卸载脚本
    Install.bat 文件:

    %SystemRoot%Microsoft.NETFrameworkv4.0.30319InstallUtil.exe "%~dp0%WindowsServiceTest.exe"
    pause
    

    Uninstall.bat文件:

    %SystemRoot%Microsoft.NETFrameworkv4.0.30319InstallUtil.exe -u "%~dp0%WindowsServiceTest.exe"
    pause
    
  • 相关阅读:
    迭代器和生成器
    案例:复制大文件
    案例:使用seek倒查获取日志文件的最后一行
    Leetcode165. Compare Version Numbers比较版本号
    Leetcode137. Single Number II只出现一次的数字2
    Leetcode129. Sum Root to Leaf Numbers求根到叶子节点数字之和
    Leetcode116. Populating Next Right Pointers in Each Node填充同一层的兄弟节点
    Leetcode114. Flatten Binary Tree to Linked List二叉树展开为链表
    Leetcode113. Path Sum II路径总和2
    C++stl中vector的几种常用构造方法
  • 原文地址:https://www.cnblogs.com/LoveTomato/p/8584026.html
Copyright © 2011-2022 走看看