2014-02-24 59 views
1

我有一個每分鐘運行一次的窗口服務。我還使用了List<User>(其中User是我的課程)的對象來保存用戶列表。服務做了兩個任務每分鐘運行一次窗口服務

  1. 獲取從數據庫中的用戶,並添加List<User>
  2. 發送短信的反對用戶和從List<User>

對象我用System.Timers.Timer類刪除用戶每分鐘運行一次服務。但我面臨的問題是,有些時候服務跳過一些用戶發送短信。所以我對我的方法有疑問,有人可以告訴我,我正在以正確的方式做這件事,或者我可以以另一種方式做到這一點?

編輯

List<User> ListUser = new List<User>(); 
bool IsReadyToExecute = false; 

public Service() 
{ 
    //Main(); 
    InitializeComponent(); 
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); 
    _timer.Interval = 1 * 1000; 
} 
protected override void OnStart(string[] args) 
{ 
    MessageLog("Service Start", "Service Start at: " + DateTime.Now.ToString()); 
    this._timer.Enabled = true; 
    _timer.Start(); 
} 
protected override void OnStop() 
{ 
    MessageLog("Service Stop", "Service Stop at: " + DateTime.Now.ToString());   
    this._timer.Enabled = false; 
    _timer.Stop(); 
} 
public void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
{ 
    MessageLog("Timer Start", "Call from _timer_Elapsed at: " + DateTime.Now.ToString()); 
    this.Main(); 
} 
private void Main() 
{ 
    if (!IsReadyToExecute) 
    { 
     if (DateTime.Now.Second == 0) 
     { 
      _timer.Interval = 1 * 60 * 1000; 
      IsReadyToExecute = true; 
     } 
     else 
     { 
      return; 
     } 
    } 
    if (IsReadyToExecute) 
    { 
     CreateUser(); 
     InsertUser(); 
    } 
} 
+0

這將是幾乎不可能猜出這些問題可能是,如果你不至少發佈有關定時器短信發送代碼。這可能是一種種族競爭條件。可能是代碼中的錯誤。沒有看到代碼就無法知道。 –

+0

我編輯問題@DavidKhaykin –

+0

這行'if(DateTime.Now.Second == 0)'的用途是什麼?你還應該發佈代碼(a)填充'List ',並且還有代碼從那裏刪除條目。具體而言,更新數據庫以瞭解哪些用戶已發送消息的代碼。這可能在某處,當新列表被獲取時,它將排除某些用戶,具體取決於您如何獲取/更新已處理用戶的狀態。 –

回答

0

您也可以嘗試這種結構

other using ..... 

using System.Threading; 

public partial class YourService : ServiceBase 
{ 
    bool StopMe = false; 

    protected override void OnStart(string[] args) 
    { 
     MessageLog("Service Start", "Service Start at: " + DateTime.Now.ToString()); 
     this.StopMe = false; 
     this.StartTheThread();  
    } 
    protected override void OnStop() 
    { 
     this.StopMe = true; 
    } 

    Thread SMSSender; 
    private void StartTheThread() 
    { 
     ThreadStart st = new ThreadStart(DoProcess); 
     SMSSender = new Thread(st); 
     SMSSender.Start(); 
    } 

    private void DoProcess() 
    { 
     while(!this.StopMe) 
     { 
      MessageLog("Timer Start", "Call from thread loop at: " + DateTime.Now.ToString()); 
      List<User> ListUser = new List<User>(); 
      //Code/function to be called to populate ListUser 

      foreach(User usr in ListUser) 
      { 
       //Code/function to be called to send sms here 

       if (this.StopMe) break; //stop the thread when stop flag is set 
      } 


      Thread.Sleep(60*1000); //sleep for 1 minute 
     } 

     MessageLog("Service Stop", "Service Stop at: " + DateTime.Now.ToString()); 
    } 
} 
相關問題