windows服務創建

https://www.cnblogs.com/wyt007/p/8675957.html

以下是安装命令、启动服务命令、停止服务命令、卸载服务命令:

    安装命令:C:WindowServiceInstallUtil.exe C:WindowServiceOrganizClientSocketService.exe

    启动服务命令:net start 搜才Organiz客户端数据同步服务

    关闭服务命令:net stop 搜才Organiz客户端数据同步服务

    卸载服务命令:C:WindowServiceInstallUtil.exe -u C:WindowServiceOrganizClientSocketService.exe

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

using System.IO;

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

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
        timer.Interval = 5000;//每5秒执行一次
        timer.Enabled = true;
    }

    //定时执行事件
    private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
    {
        //业务逻辑代码
    }

    protected override void OnStart(string[] args)
    {
        this.WriteLog("搜才Organiz客户端数据同步服务:【服务启动】");
    }

    protected override void OnStop()
    {
        this.WriteLog("搜才Organiz客户端数据同步服务:【服务停止】");
    }
    protected override void OnShutdown()
    {
        this.WriteLog("搜才Organiz客户端数据同步服务:【计算机关闭】");
    }

    #region 记录日志
    /// <summary>
    /// 记录日志
    /// </summary>
    /// <param name="msg"></param>
    private void WriteLog(string msg)
    {

        //string path = @"C:log.txt";

        //该日志文件会存在windows服务程序目录下
        string path = AppDomain.CurrentDomain.BaseDirectory + "\log.txt";
        FileInfo file = new FileInfo(path);
        if (!file.Exists)
        {
            FileStream fs;
            fs = File.Create(path);
            fs.Close();
        }

        using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine(DateTime.Now.ToString() + "   " + msg);
            }
        }
    }
    #endregion
}

}

原文地址:https://www.cnblogs.com/ellafive/p/13711209.html