1---开始配置文件

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  <appSettings>

    <!--执行间隔数,单位为秒-->
    <add key="runStep" value="10"/>
    <!--执行时间段_开始-->
    <add key="runBeginHour" value="0"/>
    <add key="runBeginMinute" value="0"/>
    <add key="runBeginSecond" value="0"/>
    <!--执行时间段_结束-->
    <add key="runEndHour" value="23"/>
    <add key="runEndMinute" value="59"/>
    <add key="runEndSecond" value="59"/>
    <!--数据同步时间间隔-->
    <add key ="BaseSyncInterval" value ="10000"/>
  </appSettings>

  <log4net>
    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\\"/>
      <param name="AppendToFile" value="true"/>
      <param name="MaxSizeRollBackups" value="100"/>
      <param name="MaxFileSize" value="10240"/>
      <param name="StaticLogFileName" value="false"/>
      <param name="DatePattern" value="yyyyMM\\yyyy-MM-dd&quot;.log&quot;"/>
      <param name="RollingStyle" value="Date"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="----------header---------- %n日志时间:%d %n日志级别:%-5p %n日 志 类:%c%n%m%n----------footer----------%n"/>
      </layout>
    </appender>
    <logger name="Mylogger">
      <level value="ALL"/>  ---设置记录级别,这里很重要Error,Info,Debug等,如果不设置,日志中将不记录这些操作日志
      <appender-ref ref="ErrorAppender"/>
    </logger>
  </log4net>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

2---创建LoggerHelper类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;

namespace BaseDataSyncWinService
{
    /// <summary>
    /// 写日志
    /// </summary>
    public class Log4NetHelper
    {
        private Log4NetHelper() { }

        private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger("Mylogger");

        public static ILog Log
        {
            get
            {
                return _Log;
            }
        }

       //设置Logger配置

       public static void SetConfig()
        {
            log4net.Config.XmlConfigurator.Configure();
        }
        public static void WriteLog(string message)
        {
            Log.Error(message);
        }
        public static void WriteLog(Exception exception)
        {
            if (exception == null)
                return;
            string error = "Message:" + exception.Message
                + Environment.NewLine
                + "Source:" + exception.Source
                + Environment.NewLine
                + "StackTrace:" + exception.StackTrace;
            Log.Error(error);
        }
    }
}

3-- 项目中使用

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.Threading;
using System.Configuration;

namespace BaseDataSyncWinService
{
    public partial class BaseDataSyncService : ServiceBase
    {
        private bool isRun;             //是否一直运行
        private int runStep;            //执行间隔数
        private DateTime runBegin;      //运行时间段--开始
        private DateTime runEnd;        //运行时间段--结束

        public BaseDataSyncService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 是否在规定的时间段内
        /// </summary>
        /// <param name="begin">运行时间段--开始</param>
        /// <param name="end">运行时间段--结束</param>
        /// <returns></returns>
        private bool IsCanRun(DateTime begin, DateTime end)
        {
            bool tof = false;

            //取时分化数
            int iBegin = begin.Hour * 60 * 60 + begin.Minute * 60 + begin.Second;
            int iEnd = end.Hour * 60 * 60 + end.Minute * 60 + end.Second;
            int iNow = DateTime.Now.Hour * 60 * 60 + DateTime.Now.Minute * 60 + DateTime.Now.Second;

            //返回对比
            tof = iNow >= iBegin && iNow <= iEnd;

            return tof;
        }

        /// <summary>
        /// 设置时间,年月日均取当前系统时间
        /// </summary>
        /// <param name="hour">小时的数值</param>
        /// <param name="minute">分钟的数值</param>
        /// <param name="second">秒的数值</param>
        /// <returns></returns>
        private DateTime SetTime(int hour, int? minute = null, int? second = null)
        {
            if (minute == null)
                minute = DateTime.Now.Minute;
            if (second == null)
                second = DateTime.Now.Second;

            return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minute.Value, second.Value);
        }
        private void ProcessTask()
        {
            isRun = true;

            //初始化运行时间
            DateTime runTime = DateTime.Now.AddSeconds(-runStep);

            //持续运行
            while (isRun)
            {
                try
                {
                    //时间段
                    if (IsCanRun(runBegin, runEnd))
                    {
                        if ((DateTime.Now - runTime).TotalSeconds > runStep)
                        {
                            //执行同步操作
                            BaseSyncTaskHelper.ExecuteBaseSyncTask();
                            //写日志
                            Log4NetHelper.WriteLog("服务正常运行中,操作结果为成功---时间为:" + DateTime.Now + System.Diagnostics.EventLogEntryType.Information);
                            runTime = DateTime.Now;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //往Windows日志写出错信息
                    Log4NetHelper.WriteLog("BaseDataSyncWinService +错误信处:"
                        + ex.Message + Environment.NewLine
                        + "信息来源:" + ex.Source
                        + Environment.NewLine + "跟踪信息:" + ex.StackTrace
                        + EventLogEntryType.Error);
                }

                //休眠指定时间
                Thread.Sleep(runStep * 1000);
            }
        }

        protected override void OnStart(string[] args)
        {
            #region 读取配置
            try
            {
                Log4NetHelper.SetConfig();
                runStep = int.Parse(ConfigurationManager.AppSettings["runStep"]);
                runBegin = SetTime(
                    int.Parse(ConfigurationManager.AppSettings["runBeginHour"]),
                    int.Parse(ConfigurationManager.AppSettings["runBeginMinute"]),
                    int.Parse(ConfigurationManager.AppSettings["runBeginSecond"]));
                runEnd = SetTime(
                    int.Parse(ConfigurationManager.AppSettings["runEndHour"]),
                    int.Parse(ConfigurationManager.AppSettings["runEndMinute"]),
                    int.Parse(ConfigurationManager.AppSettings["runEndSecond"]));
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteLog("BaseDataSyncWinService +错误信处:"
                       + ex.Message + Environment.NewLine
                       + "信息来源:" + ex.Source
                       + Environment.NewLine + "跟踪信息:" + ex.StackTrace
                       + EventLogEntryType.Error);
                throw ex; //继续往外抛。。。配置错误,无法继续的
            }
            #endregion

            Thread tProcessTask = new Thread(ProcessTask);
            tProcessTask.Start();
        }

        protected override void OnStop()
        {
            try
            {
                isRun = false;
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteLog("BaseDataSyncWinService +错误信处:"
                       + ex.Message + Environment.NewLine
                       + "信息来源:" + ex.Source
                       + Environment.NewLine + "跟踪信息:" + ex.StackTrace
                       + EventLogEntryType.Error);
            }
        }
    }
}

posted on 2013-05-16 09:59  W晴空  阅读(307)  评论(0)    收藏  举报