C# 在.NET中,多个计时器的行为不稳定
我正在构建一个应用程序,它以数据库中列出的特定间隔运行一系列程序 计划有三种方式:C# 在.NET中,多个计时器的行为不稳定,c#,visual-studio,timer,windows-services,C#,Visual Studio,Timer,Windows Services,我正在构建一个应用程序,它以数据库中列出的特定间隔运行一系列程序 计划有三种方式: 以一定的频率(每天一定次数) 在每天的特定时间 以特定时间之间的频率,即在02:00-04:00之间4次 当用一种时间表运行一个程序时,我的程序运行得非常好,而且时间表安排得非常正确。 但是,当我尝试一次运行多个程序和多种类型的日程安排时,问题似乎出现了。 时间表变得极不稳定,会多次打开同一个程序,或者运行过去在特定时间安排的程序。 我有一个计算下一个事件的精确毫秒数的函数。在debug中,我每次计算时都会记
- 以一定的频率(每天一定次数)
- 在每天的特定时间
- 以特定时间之间的频率,即在02:00-04:00之间4次
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;
}
每次为每个程序和该程序的每个时间表创建一个此类的新版本。因此,每个计时器和程序都独立运行
以下是Scheduled Tasks类的实例化方式:
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);
}
}
}
private void startScheduledTasks()
{
List taskSchedule=SystemFunctions.getTaskSchedules();
if(任务计划!=null)
{
foreach(任务计划中的任务计划currentTask)
{
ScheduledTask ScheduledTask=新ScheduledTask();
scheduledTask.taskSchedule=currentTask;
System.Timers.Timer Timer=新的System.Timers.Timer();
timer.Interval=SystemFunctions.determineNextTaskEvent(currentTask);
timer.appeated+=新系统.Timers.ElapsedEventHandler(scheduledTask.OnTimer);
timer.Start();
currentTask.timerservice=计时器;
添加(scheduledTask);
}
}
}
正如我所说,我已经验证了ms从SystemFunctions.determineNextTaskEvent(currentTask)接收到的消息代码>是准确的
有人知道是什么导致了这种行为吗?问题是你启动了过多的计时器,而且从不停止它们
我怀疑您想要设置为false
。默认为true
您是否停止过计时器?我只在服务结束时停止计时器。。。或者,当我需要修改磁盘上的程序时,我不太熟悉Visual Studio如何处理计时器,似乎我将它们视为Android Runnable。。。计时器是否在VS中自动重新启动?我想一旦调用“OnTimer”,它就需要重新初始化?我想你可能会感兴趣。哈哈,是的,这确实非常有用xD谢谢!