写在前面
FluentScheduler是.Net平台下的一个自动任务调度组件,以前经常用的是Quarz.Net,相对而言FluentScheduler的定时配置更为直观,可直接用接口进行参数化设置,对Cron表达式有恐惧症的人来说简直就是福音,使用起来非常方便。
老规矩从NuGet获取该组件
代码实现
public class SchedulerTester
{
public static void TestAddJob()
{
JobManager.Initialize();
JobManager.AddJob(
() => Console.WriteLine("1 minutes just passed."),
s => s.ToRunEvery(1).Minutes()
);
}
public static void TestUseRegistry()
{
var registry = new Registry();
registry.Schedule<MyJob>().ToRunNow().AndEvery(2).Seconds();
registry.Schedule<MyJob>().ToRunOnceIn(5).Seconds();
registry.Schedule(() => Console.WriteLine("It's 9:15 PM now.")).ToRunEvery(1).Days().At(21, 15);
//registry.Schedule<MyComplexJob>().ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
registry.Schedule<MyComplexJob>().ToRunNow().AndEvery(1).Seconds();
registry.Schedule<MyJob>().AndThen<MyOtherJob>().ToRunNow().AndEvery(5).Minutes();
JobManager.Initialize(registry);
}
public static void TestMyRegistry()
{
JobManager.Initialize(new MyRegistry());
}
}
public class MyRegistry : Registry
{
public MyRegistry()
{
// Schedule an ITask to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Seconds();
// Schedule an ITask to run once, delayed by a specific time interval.
Schedule<MyJob>().ToRunOnceIn(5).Seconds();
// Schedule a simple task to run at a specific time
Schedule(() => Console.WriteLine("Timed Task - Will run every day at 9:15pm: " + DateTime.Now)).ToRunEvery(1).Days().At(21, 15);
// Schedule a more complex action to run immediately and on an monthly interval
Schedule(() =>
{
Console.WriteLine("Complex Action Task Starts: " + DateTime.Now);
Thread.Sleep(1000);
Console.WriteLine("Complex Action Task Ends: " + DateTime.Now);
}).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
// Schedule a job using a factory method and pass parameters to the constructor.
Schedule(() => new MyComplexJob("Foo", DateTime.Now)).ToRunNow().AndEvery(2).Seconds();
//Schedule multiple tasks to be run in a single schedule
Schedule<MyJob>().AndThen<MyOtherJob>().ToRunNow().AndEvery(1).Minutes();
}
}
public class MyJob : IJob
{
public void Execute()
{
Console.WriteLine("MyJob is Executed");
}
}
public class MyOtherJob : IJob
{
public void Execute()
{
Console.WriteLine("MyOtherJob is Executed");
}
}
public class MyComplexJob : IJob
{
private string _name { get; set; }
private DateTime _date { get; set; }
public MyComplexJob(string name, DateTime dateTime)
{
this._name = name;
this._date = dateTime;
}
public void Execute()
{
Console.WriteLine($"MyComplexJob is Executed, name is {_name}, datetime:{_date.ToShortDateString()}");
}
}
调用示例:
SchedulerTester.TestUseRegistry();
SchedulerTester.TestMyRegistry();
SchedulerTester.TestAddJob();
执行结果