timer_Elapsed() 事件未触发

timer_Elapsed() Event not firing

我在 Windows 服务中使用计时器 OnStart() 方法处理 timer_Elapsed() 每 5 分钟检查一次事件。

但是 timer_Elapsed() 不是 firing/calling 5 分钟后,如果我在下面的代码中做错了什么,请纠正我。

        protected override void OnStart(string[] args)
        {
            try
            {
                genLogs.WriteErrorLog("Service Started OnStart.");
                //int tmStart = Convert.ToInt32(ConfigurationManager.AppSettings["tim"]);
                using (Timer timer = new Timer(30000))  //  (1000 * 5 * 60) for 5 minutes
                {
                    timer.Elapsed += timer_Elapsed;
                    timer.Start();
                    //Console.WriteLine("Timer is started");
                    genLogs.WriteErrorLog("Timer is started.");
                    //Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
            }

        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                genLogs.WriteErrorLog("Service Started Checking Windows Services and Web AppPools.");

                serviceLogic.InsertStatus();

                genLogs.WriteErrorLog("Service Calls Send SendEmails Method.");
                serviceLogic.SendInfo();
            }
            catch (Exception ex)
            {
                genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
            }
        }

我认为这可能是因为您是在 using 块中进行的。

using (Timer timer = new Timer(30000))  //  (1000 * 5 * 60) for 5 minutes
            {
                timer.Elapsed += timer_Elapsed;
                timer.Start();
                //Console.WriteLine("Timer is started");
                genLogs.WriteErrorLog("Timer is started.");
                //Console.ReadLine();
            } <- Your timer stops existing here

在 using 块中执行它与说 timer.Dispose(); 相同它处理计时器,因此它不能调用任何方法。 这应该有效:

Timer timer = new Timer(30000)
timer.Elapsed += timer_Elapsed;
timer.Start();

处理您的计时器将无法 运行 回调。

如果您想处理它,您必须同步该调用。

检查这个 post -> How do I gracefully stop a System.Threading.Timer?