windows 服务(可以控制台调试)

Posted on 2014-03-17 15:40  哥德巴赫猜  阅读(210)  评论(0编辑  收藏  举报

using System;
using System.Collections.Generic;

using System.ServiceProcess;
using System.Text;

namespace NeoSuiteCIMS_FW
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            string sw = AppConfig.GetConfig("switch");
            //启动服务
            if (!string.IsNullOrEmpty(sw) && sw == "1")
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new Service1()
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                //存储过程的名字
                string proName = "p_result";
                //控制台调试
                ServiceConsole.Execute(proName);
            }

        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
using System.Text.RegularExpressions;

namespace NeoSuiteCIMS_FW
{
    public partial class Service1 : ServiceBase
    {
        Timer timer1 = new Timer();
        int timeout = Convert.ToInt32(AppConfig.GetConfig("timeout"));
        public Service1()
        {
            InitializeComponent();

            //每天24点执行服务,如果第一次启动服务的时间不是24点,计算时间间隔
            if (DateTime.Now.Hour != 0)
            {
                //DateTime nextDay = DateTime.Now.AddDa=ys(1).Date;
                DateTime nextDay = DateTime.Now.AddMinutes(timeout);
                TimeSpan ts = nextDay - DateTime.Now;
                timer1.Interval = Convert.ToInt32(ts.TotalMilliseconds);
            }
            timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
        }

        protected override void OnStart(string[] args)
        {
            timer1.Start();
            LogHelper.Info("服务启动:" + DateTime.Now.ToString());
        }

        protected override void OnStop()
        {
            timer1.Stop();
            LogHelper.Info("服务停止:" + DateTime.Now.ToString());
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //存储过程的名字
                string proName = "p_result";
                ServiceConsole.Execute(proName);
            }
            catch (Exception ex)
            {
                LogHelper.Error("服务执行中出错:" + ex.Message);
            }
        }
    }
}

Copyright © 2024 哥德巴赫猜
Powered by .NET 9.0 on Kubernetes