我正在考虑实施一个“心跳”流程来全天执行大量重复的清理任务。
这似乎是使用命令模式的好机会,所以我有一个如下所示的界面:
public interface ICommand
{
void Execute();
bool IsReady();
}
然后,我创建了几个要运行的任务。这是一个基本示例:
public class ProcessFilesCommand : ICommand
{
private int secondsDelay;
private DateTime? lastRunTime;
public ProcessFilesCommand(int secondsDelay)
{
this.secondsDelay = secondsDelay;
}
public void Execute()
{
Console.WriteLine("Processing Pending Files...");
Thread.Sleep(5000); // Simulate long running task
lastRunTime = DateTime.Now;
}
public bool IsReady()
{
if (lastRunTime == null) return true;
TimeSpan timeSinceLastRun = DateTime.Now.Subtract(lastRunTime.Value);
return (timeSinceLastRun.TotalSeconds > secondsDelay);
}
}
最后,我的控制台应用程序在这个循环中运行,寻找等待添加到 ThreadPool 的任务:
class Program
{
static void Main(string[] args)
{
bool running = true;
Queue<ICommand> taskList = new Queue<ICommand>();
taskList.Enqueue(new ProcessFilesCommand(60)); // 1 minute interval
taskList.Enqueue(new DeleteOrphanedFilesCommand(300)); // 5 minute interval
while (running)
{
ICommand currentTask = taskList.Dequeue();
if (currentTask.IsReady())
{
ThreadPool.QueueUserWorkItem(t => currentTask.Execute());
}
taskList.Enqueue(currentTask);
Thread.Sleep(100);
}
}
}
除了我在操作系统课上所做的一些工作之外,我对多线程没有太多经验。但是,据我所知,我的线程都没有访问任何共享状态,所以它们应该没问题。
对于我想做的事情,这看起来像是一个“OK”的设计吗?你有什么要改变的吗?