2011-05-12 115 views
1

一個人能幫助我嗎?投票服務 - C#

我正在創建一個windows服務,連接到一個sql數據庫,並檢查表中的日期,並將其與今天的日期進行比較,並更新該數據庫中的字段,例如,如果日期等於今天的日期那麼該字段將設置爲true。

我遇到的問題是,當我啓動服務時,它不會那樣做,但是當我以正常形式進行操作時,它完美地工作。

我的代碼如下:

//System.Timers 
Timer timer = new Timer(); 
protected override void OnStart(string[] args) 
{ 
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); 
    timer.Interval = 60000; 
    timer.Enabled = true; 
} 

private void OnElapsedTime(object source, ElapsedEventArgs e) 
{ 
    int campid = 0; 
    var campRes = new ROS.Process.CampaignServiceController().GetCampainInfo(); 

    foreach (var s in campRes) 
    { 
     campid = s.CampaignId; 

     if (s.CampEndDate.Date < DateTime.Today.Date) 
     { 
      //WriteDataToFile("Not Active : " + campid.ToString()); 
      new ROS.Process.CampaignServiceController().SetCampainStatusFalse(campid); 
     } 
     else 
     { 
      //WriteDataToFile("Active : " + campid.ToString()); 
      new ROS.Process.CampaignServiceController().SetCampainStatusTrue(campid); 
     } 
    } 
} 
+1

您可以驗證'OnElapsedTime'甚至運行? – mellamokb 2011-05-12 16:18:12

+1

失敗的部分是什麼?您是否使用記錄器來檢查是否觸發了onelapsed方法? – soandos 2011-05-12 16:18:45

+0

是的,我可以驗證,因爲我運行它在一個正常的Windows窗體,它的工作完美 – greame 2011-05-12 16:21:08

回答

0

設置Timer.AutoReset =真。否則它只會做一次工作。但最好在Windows服務中使用線程。

啊,是的。 autoreset默認爲true。我也把它放在我的代碼中: GC.KeepAlive(myTimer); 所以gc不會刪除它,如果它是無效的。

+0

但它不是真的,如果你省略Timer.AutoReset編譯器假定它是真的? – greame 2011-05-12 16:25:00

+0

對不起,你是對的。嘗試gc方法。 – ibram 2011-05-12 16:31:32

+0

好,所以你說默認情況下垃圾收集器丟棄計時器,當它不在ontimeelapsed事件? – greame 2011-05-12 16:38:51

7

這樣做的另一種方法是等待事件而不是使用計時器。

public class PollingService 
    { 
     private Thread _workerThread; 
     private AutoResetEvent _finished; 
     private const int _timeout = 60*1000; 

     public void StartPolling() 
     { 
      _workerThread = new Thread(Poll); 
      _finished = new AutoResetEvent(false); 
      _workerThread.Start(); 
     } 

     private void Poll() 
     { 
      while (!_finished.WaitOne(_timeout)) 
      { 
       //do the task 
      } 
     } 

     public void StopPolling() 
     { 
      _finished.Set(); 
      _workerThread.Join(); 
     } 
    } 

在服務

public partial class Service1 : ServiceBase 
    { 
     private readonly PollingService _pollingService = new PollingService(); 
     public Service1() 
     { 
      InitializeComponent(); 
     } 

     protected override void OnStart(string[] args) 
     { 
      _pollingService.StartPolling(); 
     } 

     protected override void OnStop() 
     { 
      _pollingService.StopPolling(); 
     } 

    }