System.Timers.Timer 可以提供帮助。
首先,任务的基本类,您可能会通过数据库或其他方式拥有它。
public class Task
{
public Task()
{
}
public Task(String tName, Int32 iInterval, Int16 iPriority)
{
this.taskName = tName;
this.nextInterval = iInterval;
this.priority = iPriority;
}
private String taskName = String.Empty;
public String TaskName
{
get
{
return this.taskName;
}
set
{
this.taskName = value;
}
}
private Int32 nextInterval = 1;
public Int32 NextInterval
{
get
{
return this.nextInterval;
}
set
{
this.nextInterval = value;
}
}
private Int16 priority = 1;
public Int16 Priority
{
get
{
return this.priority;
}
set
{
this.priority = value;
}
}
}
然后是如何执行部分。
public class ExecuteTasks
{
private System.Timers.Timer myTimer = new System.Timers.Timer();
private Int32 TaskIndex = 0;
private Int32 TaskCount = 3;
protected void StartExecution()
{
myTimer.Interval = 1;
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
myTimer.Start();
}
void myTimer_Elapsed(object sender, EventArgs e)
{
myTimer.Stop();
if (TaskIndex < TaskCount)
{
Task aTask = GetTasks()[TaskIndex++];
StartTask(aTask.TaskName);
SetNextTaskTimer(aTask.NextInterval);
}
}
void SetNextTaskTimer(Int32 Seconds)
{
myTimer.Interval = (Seconds * 1000) - DateTime.Now.Millisecond - 1;//Interval is set in miliseconds
myTimer.Start();
}
void StartTask(String TaskName)
{
ProcessStartInfo objStartInfo = new ProcessStartInfo();
objStartInfo.FileName = TaskName;
Process objProcess = new Process();
objProcess.StartInfo = objStartInfo;
objProcess.Start();
}
//You will be reading your tasks from your database or a file
List<Task> GetTasks()
{
List<Task> lstTasks = new List<Task>();
lstTasks.Add(new Task("Task A", 2, 1));
lstTasks.Add(new Task("Task B", 10, 2));
lstTasks.Add(new Task("Task C", 60, 3));
return lstTasks.OrderBy(le => le.Priority).ToList();
}
}
当给定时间过去时,我已经启动了一些进程。(您需要为该过程的开始提供正确的路径。即类似
ProcessStartInfo objStartInfo = new ProcessStartInfo();
objStartInfo.FileName = "C:\\Windows\\notepad.exe";
而不仅仅是任务名称。
最后触发执行部分。
ExecuteTasks iExecute = new ExecuteTasks();
iExecute.StartExecution();
对于多线程,您可以使用适合您需要的锁定机制、监控类等。IE
lock(obj)//lock on an object
{
ExecuteTasks iExecute = new ExecuteTasks();
iExecute.StartExecution();
}