2012-03-30 72 views
2

我繼承了Windows服務以提升我的公司。目前,該服務每天在指定的開始時間在數據庫中打印特定記錄的報告。我添加了一個條件來設置第二個開始時間來運行刪除特定記錄的相同報告。我遇到的問題是我設置了兩個單獨的開始時間(通常大約相隔15分鐘),它似乎跳過了第一個開始時間,並且只在報告文件已經存在時才運行第二個開始時間。Windows服務上的多個計時器未正確啓動

public partial class Service1 : ServiceBase 
{ 
    Timer t1; 
    Timer t2; 
    bool Condition; 

    public Service1() 
    { 
     InitializeComponent(); 
    } 
    protected override void OnStart(string[] args) 
    { 
     t1 = new Timer(); 
     t1.Interval = (1000 * 60 * 3); // 3 minutes... 
     t1.Elapsed += new ElapsedEventHandler(t1_Elapsed); 
     t1.AutoReset = true; 
     t1.Enabled = true; 

     if (Condition) //Condition is an option in the configuration to determine if this timer should even start 
     { 
      t2 = new Timer(); 
      t2.Interval = (1000 * 60 * 3); // 3 minutes... 
      t2.Elapsed += new ElapsedEventHandler(t2_Elapsed); 
      t2.AutoReset = true; 
      t2.Enabled = true; 
     } 
    } 
    private void t1_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     if (File.Exists("FileName1")) 
     { 
      string CurrentTime = DateTime.Now.ToShortDateString(); 

      if (CurrentTime == ConfigurationManager.AppSettings["StartTime"].ToString()) 
      { 
       //Print Report 
      } 
     } 
     else 
     { 
      //Print Report 
     } 
    } 
    private void t2_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     if (File.Exists("FileName2")) 
     { 
      string CurrentTime2 = DateTime.Now.ToShortDateString(); 

      if (CurrentTime2 == ConfigurationManager.AppSettings["StartTime2"].ToString()) 
      { 
       //Print Report 2 
      } 
     } 
     else 
     { 
      //Print Report 2 
     } 
    }   
    protected override void OnStop() 
    { 
     t1.Enabled = false; 
     t2.Enabled = false; 
    } 
} 

我想不通爲什麼這第一個跳過。兩者都會檢查文件是否存在,如果不存在則打印。下次運行時,第二份報告將在預定時間打印,但第一份報告會跳過。我似乎無法弄清楚我錯過了什麼。

+0

爲什麼你使用兩個定時器呢?將任務分解爲單獨的方法,並從單個計時器過去的事件中調用方法,並在計時器已用事件中檢查您的條件。 – JamieSee 2012-03-30 20:30:20

+0

注意,你應該使用[計劃任務](http://stackoverflow.com/questions/7394806/creating-scheduled-tasks)。服務+計時器=設計氣味。通過這樣做,你可以避免大部分的問題。另外,你比較時間的方式看起來超級平庸。你的問題可能在那裏。很難說沒有看到StartTime和StartTime2,因爲它們實際上在你的配置文件中。 – Will 2012-03-30 20:30:22

+0

我原本是將它作爲一個計時器上的兩個單獨的方法,但我遇到了某種不同的問題,不幸的是,我不記得它是什麼。此後我做了一些其他更改,以便將其更改回來可能有效。 – LDWisdom 2012-03-30 20:46:11

回答

2

你有沒有機會使用錯誤的定時器? 我記得大約有2或3種定時器在.net:

System.Timers.Timer 

System.Thread.Timer 

System.Windows.Forms.Timer 

我相信,在窗口服務,你應該使用前兩個中的一個,更可能System.Timers.Timer,因爲它通過提供線程safetiness SynchronizationObject屬性: System.Timers.Timer vs System.Threading.Timer