windows服务的通常写法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using log4net;
using System.Configuration;
namespace Beyondbit.Comac.DocumentsUserSynch
{
    partial class UsersSynch : ServiceBase
    {
        private System.Timers.Timer theTimer = new System.Timers.Timer();//定时器
        private double timespan;//服务执行的时间间隔
        public UsersSynch()
        {
            InitializeComponent();
            this.theTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.theTimer_Elapsed);

        }
        private ILog _Log = log4net.LogManager.GetLogger("Beyondbit.Comac.DocumentSyn");
        protected ILog Log
        {
            get
            {
                return _Log;
            }
        }
      //  private Thread _WorkThread;
        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            //_WorkThread = new Thread(new ThreadStart(WorkThreadHandle));
            //_WorkThread.Start();
            try
            {
                Log.Debug("-===========OnStart方法!-============-");
                theTimer.Start();
                timespan = Convert.ToDouble(ConfigurationManager.AppSettings["jianGeHour"]);
                theTimer.Interval = timespan * 60 * 60 * 1000; //转换为毫秒
                theTimer.AutoReset = true;
                theTimer.Enabled = true;
            }
            catch (Exception ex)
            {
                DateTime now = DateTime.Now;
                Log.Error("-===========OnStart(...)方法出错:" + ex.Message); 
            }
        }
              private void theTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                DateTime now = DateTime.Now;
                Log.Debug("-===========UsersSynch类,执行theTimer_Elapsed()方法!-============-时间:" + now.ToString());
                string[] shijian = (ConfigurationManager.AppSettings["dingshi"]).Split(':');
                int hour = int.Parse(shijian[0]);//
             
                if (now.Hour == hour)
                {
                    Log.Debug("-===========准备执行processUserSynch.PrecessSynchData()方法!-============-时间:" + now.ToString());
                    for (int i = 0; i < 2; i++)
                    {
                        ProcessUserSynch processUserSynch = new ProcessUserSynch();
                        processUserSynch.PrecessSynchData();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("-===========theTimer_Elapsed(...)方法出错:"+ex.Message);
            }
        }
        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            Log.Debug("-===========OnStop(),服务停止!===========-");
        }
    }
}
posted @ 2012-08-08 20:46  沐雪架构师  阅读(283)  评论(0编辑  收藏  举报