Windows服务上的多个计时器未正确启动

本文关键字:启动 计时器 服务 Windows | 更新日期: 2023-09-27 18:29:44

我继承了一项Windows服务,以便在我的公司进行增强。目前,该服务每天在指定的开始时间打印数据库中特定记录的报告。我添加了一个条件来设置第二个开始时间,以运行省略特定记录的相同报告。我遇到的问题是,我设置了两个单独的开始时间(通常间隔约15分钟),如果报告文件已经存在,它似乎跳过了第一个开始时间,只运行第二个。

    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;
    }
}

我不明白为什么第一个被跳过了。两者都会检查文件是否存在,如果不存在则打印。下次运行时,第二个报告将按计划时间打印,但第一个报告将被跳过。我似乎想不出我错过了什么。

Windows服务上的多个计时器未正确启动

是否有可能使用了错误的计时器?我记得在.Net中大约有2到3种计时器:

System.Timers.Timer
System.Thread.Timer
System.Windows.Forms.Timer

我认为在windows服务中,您应该使用前两个(更可能是System.Timers.Timer)之一,因为它通过SynchronizationObject属性提供线程安全性:System.Timers.Timer与System.Threading.Timer