本文首发于《简单、轻量、功能非常强大的C#/ASP.NET定时调度任务执行管理组件--FluentScheduler之实例篇》
上篇《推荐一个C#/ASP.NET定时任务执行管理器组件》给大家介绍了一个用于C#程序开发的组件,但具体的用法还没有做详细的说明,今天用此文来列举一下FluentScheduler的使用。
用法一:TaskManager.AddTask()方法,具体实现代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentScheduler;
namespace FluentSchedulerDemo
{
class Program
{
static void Main(string[] args)
{
TaskManager.AddTask(() =>
{
//Do something...
Console.WriteLine("Timer task,current time:{0}", DateTime.Now);
}, t =>
{
//从程序启动开始执行,然后每秒钟执行一次
t.ToRunNow().AndEvery(1).Seconds();
////带有任务名称的任务定时器
//t.WithName("TimerTask").ToRunOnceAt(DateTime.Now.AddSeconds(5));
});
Console.ReadKey();
}
}
}
这种实现是比较简单的,直接引入命名空间FluentScheduler就可以了。执行结果如图:
用法二:继承FluentScheduler的Registry类
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();
}
}
此方法需要初始化:
TaskManager.Initialize(new MyRegistry());