多个计时器在 .NET 中行为不稳定

Multiple timers behave erratically in .NET

我正在构建一个应用程序,它本质上是 运行 数据库中列出的特定时间间隔的程序列表。

可以通过 3 种方式安排节目:

当 运行使用单一类型的日程安排单个程序时,我的程序 运行 非常完美并且在正确的时间安排。 但是,当我一次尝试 运行 多个程序和一种以上的时间表时,问题似乎就出现了。 时间表变得非常不稳定,多次打开同一个节目,或者 运行s 一个节目已经安排在过去的特定时间。 我有一个函数可以计算到下一个事件的精确毫秒数。在调试中,我在每次计算时都记录了这个函数,并为哪个程序记录了日志,仔细检查这些日志后,它工作得很好......这让我相信我初始化定时器的方式可能有问题.

这是我的计划任务 class,其中 运行 是程序并创建下一个计时器:

public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
    {
        taskSchedule.process = System.Diagnostics.Process.Start(SystemFunctions.getFullExePath(taskSchedule));


        SystemFunctions.setLastTimeTaskRun(taskSchedule.id, DateTime.Now);
        taskSchedule.lastRun = DateTime.Now;

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = SystemFunctions.determineNextTaskEvent(taskSchedule);
        timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
        timer.Start();
        taskSchedule.timerservice = timer;
    }

每次为每个节目和该节目的每个时间表创建此 class 的新版本。所以每个计时器和程序 运行 都是独立的。

这是计划任务 class 的实例化方式:

private void startScheduledTasks()
    {
        List<TaskSchedule> taskSchedule = SystemFunctions.getTaskSchedules();

        if (taskSchedule != null)
        {
            foreach (TaskSchedule currentTask in taskSchedule)
            {
                ScheduledTask scheduledTask = new ScheduledTask();
                scheduledTask.taskSchedule = currentTask;
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Interval = SystemFunctions.determineNextTaskEvent(currentTask);
                timer.Elapsed += new System.Timers.ElapsedEventHandler(scheduledTask.OnTimer);
                timer.Start();
                currentTask.timerservice = timer;
                scheduledTasks.Add(scheduledTask);
            }
        }
    }

正如我所说,我已验证从 SystemFunctions.determineNextTaskEvent(currentTask); 收到的 ms 是准确的...

有谁知道是什么导致了这种行为?

问题是您启动了过多的计时器,并且从不停止它们。

我怀疑您想将 AutoReset 设置为 false默认为true.