在C#WINFORM或者是ASP.NET的WEB应用程序中,根据各种定时任务的需求,比如:每天的数据统计,每小时刷新系统缓存等等,这个时候我们得应用到定时器这个东东。
.NET Framework有自带的timer,但这个类只能完成一些简单的定时操作,比如间隔多久执行什么操作。遇到一些复杂的定时任务,如从当前时间开始,多少时间后间隔重复执行,timer类处理起来就相对困难了。经过多番查找搜索,终于找到一下比较好用的任务定时器–FluentScheduler,你可以通过Nuget来引用,用程序包管理器执行如下命令即可安装:
Install-Package FluentScheduler
using FluentScheduler;
public class MyRegistry : Registry
{
public MyRegistry()
{
// Schedule an ITask to run at an interval
Schedule<MyTask>().ToRunNow().AndEvery(2).Seconds();
// Schedule an ITask to run once, delayed by a specific time interval.
Schedule<MyTask>().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 multiple tasks to be run in a single schedule
Schedule<MyTask>().AndThen<MyOtherTask>().ToRunNow().AndEvery(5).Minutes();
}
}