如何使用FluentScheduler库在C#中安排任务?

我试图通过控制台应用程序(.Net Framework 4.5.2)熟悉C#FluentScheduler库。 以下是编写的代码:

class Program { static void Main(string[] args) { JobManager.Initialize(new MyRegistry()); } } public class MyRegistry : Registry { public MyRegistry() { Action someMethod = new Action(() => { Console.WriteLine("Timed Task - Will run now"); }); Schedule schedule = new Schedule(someMethod); schedule.ToRunNow(); } } 

此代码执行时没有任何错误,但我没有看到任何在Console上写的内容。 我在这里错过了什么吗?

您使用的库是错误的 – 您不应该创建新的Schedule
您应该使用Registry的方法。

 public class MyRegistry : Registry { public MyRegistry() { Action someMethod = new Action(() => { Console.WriteLine("Timed Task - Will run now"); }); // Schedule schedule = new Schedule(someMethod); // schedule.ToRunNow(); this.Schedule(someMethod).ToRunNow(); } } 

第二个问题是控制台应用程序将在初始化后立即退出,因此添加一个Console.ReadLine()

 static void Main(string[] args) { JobManager.Initialize(new MyRegistry()); Console.ReadLine(); } 

FluentScheduler是一个很棒的软件包,但是我会避免尝试在评论中建议的ASP.Net应用程序中使用它 – 当您的应用程序在一段时间不活动后卸载时,您的调度程序会有效停止。

更好的想法是将它托管在专用的Windows服务中。

除此之外 – 你已经要求控制台应用程序实现,所以试一试:

 using System; using FluentScheduler; namespace SchedulerDemo { class Program { static void Main(string[] args) { // Start the scheduler JobManager.Initialize(new ScheduledJobRegistry()); // Wait for something Console.WriteLine("Press enter to terminate..."); Console.ReadLine(); // Stop the scheduler JobManager.StopAndBlock(); } } public class ScheduledJobRegistry : Registry { public ScheduledJobRegistry() { Schedule() .NonReentrant() // Only one instance of the job can run at a time .ToRunOnceAt(DateTime.Now.AddSeconds(3)) // Delay startup for a while .AndEvery(2).Seconds(); // Interval // TODO... Add more schedules here } } public class MyJob : IJob { public void Execute() { // Execute your scheduled task here Console.WriteLine("The time is {0:HH:mm:ss}", DateTime.Now); } } }