我有一个应用程序(.Net Framework 2.0!),您可以在其中输入将在给定时间执行的操作。
现在我想创建一个在后台运行的进程,不做其他事情,然后等到达到给定时间并调用该操作运行。该应用程序应该运行诸如备份计算机的特定部分,启动更新,运行批处理等...后台工作程序将运行几个月不做任何其他操作。
使用下面的代码可以工作,但似乎有点难看。有没有更好的解决方案?
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);
}
非常感谢你。
答案 0 :(得分:1)
我建议使用Windows service
来实现一个每隔n秒触发一次事件的计时器。您可以从任何地方获取任务,并在服务内部将它们排队并在给定时间点火。只需检查_executeTimer_Elapsed
方法中的时间戳即可。这只是一个小样本,但它应该足以让你开始。
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();
}
}