使用Timer
平時在開發過程中,有時候圖省事,直接拖入Window控件包里的Timer控件去為我們這事情,但是今天在寫程序的時候出現異常,費了一番功夫找到問題原因,以此記錄一下。
將timer控件拖到WindowService設計中,雙擊timer生成事件,在Designer.cs中自動生成如下代碼:
private System.Windows.Forms.Timer timer1; this.timer1 = new System.Windows.Forms.Timer(this.components); this.timer1.Interval = 10000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
然后我在timer1_click事件中,編寫代碼,期望它能按時執行。事實上,在部署WindowService程序時發現它並沒起到作用。WindowService調試方法,是在服務運行時或運行后,使用VS調試中的附加進程。但在調試過程中,發現事件並未執行,通過查找msdn,發現WindowService程序中,timer控件不是這樣用的。正確的timer定義與使用如下:
private System.Timers.Timer timer1; this.timer1 = new System.Timers.Timer(); this.timer1.Enabled = true; this.timer1.Interval = 7200D; this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
這樣看起來會發現,它的聲明與事件都是不相同的,代碼很簡單。按照以上代碼,修改即可。
使用.代表根目錄
在上述timer的elapsed事件里,我寫的代碼是
//檢查日志文件刪除 if (Directory.Exists("./Logs")) { var files = Directory.GetFiles("./Logs"); //設置保存近3天的日志文件 var oldDate = DateTime.Now.AddDays(-3); foreach (var file in files) { var updateTime = File.GetLastWriteTime(file); if (updateTime < oldDate) { File.Delete(file); } } }
在目錄的判斷中發現該判斷返回false,於是意識到可能是偷懶寫.引起的,后來更換成 AppDomain.CurrentDomain.SetupInformation.ApplicationBase ,問題解決了。用.代表根目錄,在Winform程序中是可以的,但是在WindowService程序中.指向了system32。