window service 开发
为了便于window service的调试和开发。
我整理了一下代码,方便大家查阅
App.config
设置启动时间
timerStart-10点
interval-3600000 1小时检查一次
isdebug-调试模式
<!--timer-->
    <add key="timerStart" value="10" />
    <add key="interval" value="3600000" />
<!--IsDebug-->
    <add key="IsDebug" value="true" />
<!--Log-->
    <add key="logPath" value="D:\Log\" />
Program
static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            if (MyConfig.IsDebug)
            {
                //测试
                Service1 s = new Service1();
            }
            else
            {
                //正式
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                new Service1()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
    }
Service
public Service1()
        {
            InitializeComponent();
//全局异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            //运行
            RunService();
        }
        System.Timers.Timer timer1 = new System.Timers.Timer(MyConfig.interval);
        protected override void OnStart(string[] args)
        {
            //正式
            if (!MyConfig.IsDebug)
            {
                timer1.AutoReset = true;
                timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                timer1.Enabled = true;
            }
        }
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour == MyConfig.timerStart)
            {
                RunService();
            }
        }
        public void RunService()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            LogHelper.WriteLog("  <<==开始______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");
            try
            {
                //处理逻辑
                DoSomeThing();
                LogHelper.WriteLog("  <<==结束______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
                LogHelper.WriteLog(ex.StackTrace);
                LogHelper.WriteLog("  <<==结束______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");
            }
            finally
            {
                Clear();
            }
        }
        protected override void OnStop()
        {
            //正式
            timer1.Enabled = false;
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = e.ExceptionObject as Exception;
                string exStr = "\n" + "\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ex.Message + "详细信息如下:\n"
                                    + Environment.NewLine + "[InnerException]" + ex.InnerException + "\n"
                                    + Environment.NewLine + "[Source]" + ex.Source + "\n"
                                    + Environment.NewLine + "[TargetSite]" + ex.TargetSite + "\n"
                                    + Environment.NewLine + "[StackTrace]" + ex.StackTrace + "\n";
                LogHelper.WriteLog(exStr);
            }
            catch { }
            finally { }
        }
LogHelper
public class LogHelper
    {
        public static readonly string logPath = ConfigurationManager.AppSettings["logPath"];
        private static readonly object writeFile = new object();
        public LogHelper() { }
        /// <summary>
        /// 在本地写入错误日志
        /// </summary>
        /// <param name="exception"></param>
        public static void WriteLog(string debugstr)
        {
            lock (writeFile)
            {
                FileStream fs = null;
                StreamWriter sw = null;
                try
                {
                    string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                    //服务器中日志目录
                    if (!Directory.Exists(logPath))
                        Directory.CreateDirectory(logPath);
                    fs = new FileStream(logPath + "/" + filename, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine(DateTime.Now.ToString() + "     " + debugstr + "\r\n");
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Flush();
                        sw.Dispose();
                        sw = null;
                    }
                    if (fs != null)
                    {
                        //     fs.Flush();
                        fs.Dispose();
                        fs = null;
                    }
                }
            }
        }
    }
window service 开发的更多相关文章
- 【转】android 最新 NDK r8 在window下开发环境搭建 安装配置与使用 详细图文讲解,完整实际配置过程记录(原创)
		
原文网址:http://www.cnblogs.com/zdz8207/archive/2012/11/27/android-ndk-install.html android 最新 NDK r8 在w ...
 - C# window Service实现调用有UI的应用程序(关于win xp以后的window系统)
		
我开发的系统中有一接口程序(这里就称Task,是一个C#的Console Application)经常无故的死掉,导致第二天的数据不能正常解析,所以,我写了一个window service去监视Tas ...
 - android 最新 NDK r8 在window下开发环境搭建 安装配置与使用 详细图文讲解,完整实际配置过程记录(原创)
		
android 最新 NDK r8 在window下开发环境搭建 安装配置与使用 详细图文讲解,完整实际配置过程记录(原创) 一直想搞NDK开发却一直给其他事情耽搁了,参考了些网上的资料今天终于把 ...
 - window service 创建
		
1:vs中创建一个 window servece 2.右键 添加安装程序 3.更改属性视图中的Account属性为LocalService(本地服务) 更改ServiceName为你自己的服务名称 ...
 - Android NDK r8 Cygwin CDT 在window下开发环境搭建 安装配置与使用 具体图文解说
		
版权声明:本博客全部文章均为原创.欢迎交流.欢迎转载:转载请勿篡改内容,而且注明出处,谢谢! https://blog.csdn.net/waldmer/article/details/3272500 ...
 - Windows Service 开发,安装与调试
		
Visual Studio.net 2010 Windows Service 开发,安装与调试 本示例完成一个每隔一分钟向C:\log.txt文件写入一条记录为例,讲述一个Windows Servic ...
 - JAX-RS 方式的 RESTful Web Service 开发
		
JAX-RS 方式的 RESTful Web Service 开发 ——基于 CXF+Spring 的实现 Web Service 目前在风格上有两大类,一个是基于 SOAP 协议,一个是完全遵循 H ...
 - C# window service的创建
		
其实我也是第一次在博客园写博客,看到那些高手说自己要多动手写博客,于是乎自己也尝试尝试. 废话不多说.这几天在研究window service,通过查找各种大神写的博客,我终于成功的自己写出来了. 下 ...
 - 创建 window service 定时任务
		
参考文章:http://www.cnblogs.com/jack-liang/archive/2011/05/20/2051743.html 前段时间做过一个项目,前端系统提供添加定时任务,后端系统要 ...
 
随机推荐
- Linux DNS原理简介及配置
			
Linux DNS原理简介及配置 DNS简介 DNS原理 域名解析的过程 资源记录 DNS BIND安装配置 一.简介 一般来讲域名比IP地址更加的有含义.也更容易记住,所以通常用户更习惯输入域名来访 ...
 - co模块源码学习笔记
			
// Sorrow.X --- 添加注释,注释纯属个人理解 /** * slice变量 引用 数组的 slice方法 */ var slice = Array.prototype.slice; /** ...
 - kubernetes session回话保持
			
1.Nginx 版本 root@ingress-nginx-controller-4b75b:/# /usr/sbin/nginx -vnginx version: nginx/1.13.9 2.in ...
 - ES6-课程介绍
			
ES6 可以提高开发效率,把ES3比做斧头,ES5比做锯子,那么ES6就是电锯. ES6新特性 默认参数.字符串模板.结构赋值.箭头函数.set\mat .异步操作.类和对象 .模块化
 - cssie7.0兼容
			
http://www.w3dev.cn/article/20140328/IE7-float-left-touch-border-inner-break.aspx
 - swift 各种学习
			
swift使用cocoapods引用oc第三方库 1. 创建桥接文件 2. 在主工程的 build Settings 搜索 bridge 设置 Objective-C Bridging Headi ...
 - Pairproject 移山之道  阅读随笔和一些问题
			
首先不得不承认这本书的写作方式很独特,不像其他的计算机类的图书那样枯燥,让人读起来感觉很有意思,他也颠覆了我对计算机类图书的看法,这种写作方式值得我们学习. 先谈谈收获吧.读了两年大学,这是第一次写类 ...
 - 北航学堂Android客户端Beta阶段发布说明
			
在从学姐那里拿到服务接口的代码最终连通服务器之后,经过我们团队的努力,终于把前后端融合生成了我们目前的版本, 因为我们在Alpha阶段网络连接部分是一直没有搞定的,所以这个版本其实并不算是真正的Bet ...
 - #个人博客作业Week2——关于代码规范的讨论
			
<1> 这些规范都是官僚制度下产生的浪费大家的编程时间.影响人们开发效率, 浪费时间的东西. 反驳:官僚制度在一定程度下维持了社会的和谐稳定,一个没有法律.没有拥有完善的管理体制.完全崇尚 ...
 - linux内核分析第四次实验
			
实验步骤: 使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用.本次实验中我使用第20号系统调用getpid()函数,用于取得进程识别码. C代码(getpid.c): #include ...