C# 基于时间的操作的背景流程
我有一个应用程序(.Net Framework 2.0!),您可以在其中输入将在给定时间执行的操作 现在我想创建一个进程,该进程在后台运行,不做任何其他事情,然后等待到给定的时间,并调用该操作来运行。应用程序应该运行诸如备份计算机的特定部分、启动更新、运行批处理等操作。。。后台工作人员将在几个月内无所事事 使用下面的代码可以工作,但看起来有点难看。有没有更好的解决办法C# 基于时间的操作的背景流程,c#,timer,.net-2.0,C#,Timer,.net 2.0,我有一个应用程序(.Net Framework 2.0!),您可以在其中输入将在给定时间执行的操作 现在我想创建一个进程,该进程在后台运行,不做任何其他事情,然后等待到给定的时间,并调用该操作来运行。应用程序应该运行诸如备份计算机的特定部分、启动更新、运行批处理等操作。。。后台工作人员将在几个月内无所事事 使用下面的代码可以工作,但看起来有点难看。有没有更好的解决办法 while(true && !applicationClosing) { List<ExecPr
while(true && !applicationClosing)
{
List<ExecProcess> processList = LoadStoredProcesses();
List<ExecProcess> spawnedProcesses = new List<ExecProcess>();
DateTime actualTime = DateTime.Now();
foreach(ExecProcess ep in processList)
{
if(ep.ExecutionTime < actualTime)
{
ep.Execute();
spawnedProcesses.Add(ep);
}
}
RemoveSpawnedProcesses(spawnedProcesses);
Thread.Sleep(1000);
}
while(true&&!applicationClosing)
{
List processList=LoadStoredProcesss();
List spawnedProcesses=new List();
DateTime actualTime=DateTime.Now();
foreach(进程列表中的ExecProcess ep)
{
if(ep.ExecutionTime<实际时间)
{
ep.Execute();
spawnedProcesses.Add(ep);
}
}
RemovesPawnedProcess(派生进程);
睡眠(1000);
}
非常感谢。我建议使用
Windows服务
,它实现了一个计时器,每n秒触发一次事件。您可以从任何您想要的地方提取任务,并在服务中对它们进行内部排队,然后在给定的时间触发。只需检查\u executeTimer\u expressed
方法中的时间戳。这只是一个小样本,但它应该足以让您开始
public class MyService : ServiceBase
{
private Timer _executeTimer;
private bool _isRunning;
public MyService()
{
_executeTimer = new Timer();
_executeTimer.Interval = 1000 * 60; // 1 minute
_executeTimer.Elapsed += _executeTimer_Elapsed;
_executeTimer.Start();
}
private void _executeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!_isRunning) return; // logic already running, skip out.
try
{
_isRunning = true; // set timer event running.
// perform some logic.
}
catch (Exception ex)
{
// perform some error handling. You should be aware of which
// exceptions you can handle and which you can't handle.
// Blanket handling Exception is not recommended.
throw;
}
finally
{
_isRunning = false; // set timer event finished.
}
}
protected override void OnStart(string[] args)
{
// perform some startup initialization here.
_executeTimer.Start();
}
protected override void OnStop()
{
// perform shutdown logic here.
_executeTimer.Stop();
}
}
更好的解决方案是使用Windows任务计划程序我不想使用Windows任务计划程序。简而言之:我正在实现一个扩展的Windows任务调度器,它允许运行和管理我自己的应用程序。使用一个可以从消息队列中提取项目的Windows服务怎么样。e、 g.新任务被发送到队列,服务拾取并在内部对其进行排队。我不需要messagequeue,因为执行计划和执行参数存储在数据库中,我可以轻松获取它们。但我会看看我以前从未使用过的服务和消息队列。我最大的问题是“仅”如何让我的程序在规定的时间做出反应。没有类似的东西:Clock.SetNextAlarm=ep.ExecutionTime;Clock.Alarm+=新的AlarmEventHandler(RunNextProgramm);如果达到我设置的时间,windows将触发事件,那么就没有什么可做的了?