C# 支持更多日期/时间触发器的调度引擎
我发现了许多很棒的.NET调度引擎,特别是Quartz.NET看起来非常有前途。然而,我需要一个调度引擎,它不仅能让我触发日期和时间,还能触发我能想到的任何东西。例如,我可能希望在看到进程已启动、计算机被锁定、WMI事件关闭等时触发。。。除了基于日期/时间的触发器之外 我所寻找的是一个解决方案,它允许我实现适当的接口,并在满足条件时触发触发器。这样的事情已经存在了还是我自己 以下是我看过的几个:C# 支持更多日期/时间触发器的调度引擎,c#,scheduled-tasks,quartz-scheduler,C#,Scheduled Tasks,Quartz Scheduler,我发现了许多很棒的.NET调度引擎,特别是Quartz.NET看起来非常有前途。然而,我需要一个调度引擎,它不仅能让我触发日期和时间,还能触发我能想到的任何东西。例如,我可能希望在看到进程已启动、计算机被锁定、WMI事件关闭等时触发。。。除了基于日期/时间的触发器之外 我所寻找的是一个解决方案,它允许我实现适当的接口,并在满足条件时触发触发器。这样的事情已经存在了还是我自己 以下是我看过的几个: 这需要在我的.NET应用程序中运行。我考虑修改Quartz.Net以支持这种类
我更喜欢脱离现有的调度系统,这样我就不必担心实现诸如队列、优先级、线程池等繁琐的细节。。。但是我当然会做我必须做的。你可以声明一个基本的
任务类或接口,不管你喜欢哪个,它实现了bool
属性NeedsToRun
和方法Run()
然后,您可以继承每个任务的任务类(或使用委托函数、任务类型),并定义检查该任务是否需要运行所需的所有自定义需求,如果需要,则调用该特定任务的run()
方法
将您的所有任务添加到列表中
,并定期对其进行迭代,以查看实际需要运行的任务,然后瞧;您有一个非常简单但有效的调度程序
就我个人而言,我追求的是基于优先级的调度程序,而不是您所描述的事件驱动的调度程序,因此我实现了一个Func
,以确定任务是否需要运行,以及一个操作
来实际运行它。我的代码如下:
public class Task : IComparable<Task>
{
public Task(int priority, Action action, Func<bool> needsToRun, string name = "Basic Task")
{
Priority = priority;
Name = name;
Action = action;
_needsToRun = needsToRun;
}
public string Name { get; set; }
public int Priority { get; set; }
private readonly Func<bool> _needsToRun;
public bool NeedsToRun { get { return _needsToRun.Invoke(); } }
/// <summary>
/// Gets or sets the action this task performs.
/// </summary>
/// <value>
/// The action.
/// </value>
public Action Action { get; set; }
public void Run()
{
if (Action != null)
Action.Invoke();
}
#region Implementation of IComparable<in State>
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(Task other)
{
return Priority == other.Priority && Name == other.Name ? 1 : 0;
}
#endregion
}
公共类任务:i可比较
{
公共任务(int优先级,Action-Action,Func-needsToRun,string name=“基本任务”)
{
优先级=优先级;
名称=名称;
行动=行动;
_needsToRun=needsToRun;
}
公共字符串名称{get;set;}
公共int优先级{get;set;}
私有只读函数;
public bool NeedsToRun{get{return{u NeedsToRun.Invoke();}
///
///获取或设置此任务执行的操作。
///
///
///行动。
///
公共操作动作{get;set;}
公开募捐
{
如果(操作!=null)
Action.Invoke();
}
#IComparable的区域实现
///
///将当前对象与相同类型的另一个对象进行比较。
///
///
///指示要比较的对象的相对顺序的值。返回值具有以下含义:值表示小于零此对象小于参数。零此对象等于。大于零此对象大于。
///
///要与此对象进行比较的对象。
公共整数比较(任务其他)
{
返回Priority==other.Priority&&Name==other.Name?1:0;
}
#端区
}
但我认为这可以用于订阅事件,并设置一个标志,以确保NeedsToRun
在触发事件时返回true。这个类可能是一个很好的起点,我感谢您发布代码。如果我走这条路,我会让你知道的。