每分钟运行一次窗口服务

时间:2014-02-24 05:41:56

标签: c# windows

我有一个每分钟运行一次的窗口服务。我还使用了List<User>(用户是我的班级)的对象来保存用户列表。服务完成了两项任务

  1. 从数据库中提取用户并添加到List<User>
  2. 的对象
  3. 向用户发送短信,并将用户从List<User>
  4. 的对象中删除

    我使用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();
        }
    }
    

1 个答案:

答案 0 :(得分: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()); 
    }
}