看个粟子:

 1、“新建项目”——“Window服务”Windows服务操作之sc和net命令及windows任务计划

生成的目录结构

Windows服务操作之sc和net命令及windows任务计划

双击“MainService.cs”,右键点击“添加安装程序”,自动会生成Projectinstaller.cs文件以及两个安装组件,对两个组件更名并做属性设置:

Windows服务操作之sc和net命令及windows任务计划

Windows服务操作之sc和net命令及windows任务计划

Windows服务操作之sc和net命令及windows任务计划

对服务的启动与停止添加代码

using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Timers;

namespace MainService
{
    public partial class MainService : ServiceBase
    {
        private Timer time = new Timer();
        public MainService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            WriteLog("服务启动,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n");

            time.Elapsed += new System.Timers.ElapsedEventHandler(MethodEvent);
            time.Interval = 2 * 1000;//时间间隔为2秒钟
            time.Start();
        }

        protected override void OnStop()
        {
            WriteLog("服务停止,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }

        private void MethodEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            time.Enabled = false;

            string result = string.Empty;
            string startTime = DateTime.Now.ToString("HH:mm:ss");
            try
            {
                //.........

                result = "执行成功,时间为:" + startTime;
            }
            catch (Exception exp)
            {
                result = "失败,原因:" + exp.Message;
            }
            finally
            {
                WriteLog(result);

                time.Enabled = true;
            }
        }

        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="logInfo"></param>
        public void WriteLog(string logInfo)
        {
            try
            {
                string logDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                }
                string filePath = logDirectory + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                File.AppendAllText(filePath, logInfo);
            }
            catch
            {
            }
        }
    }
}
View Code

相关文章:

  • 2021-11-01
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
  • 2021-11-18
  • 2021-11-18
  • 2021-11-18
  • 2021-08-19
猜你喜欢
  • 2021-11-18
  • 2021-06-14
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-10-21
相关资源
相似解决方案