FluentScheduler是一个简单的任务调度框架,使用起来非常方便。作者的源码和例子的地址:
https://github.com/fluentscheduler/FluentScheduler
1.首先引用FluentScheduler.dll,dll数据源可通过NuGet程序包获取。打开管理解决方案的NuGet程序包,输入FluentScheduler即可。
步骤:状态栏选择 工具 - NuGet程序包管理器 – 管理解决方案的NuGet程序包,然后输入FluentScheduler即可。
2.新建Registry继承类
using System; using FluentScheduler; using System.Threading; namespace DemoProject2020 { public class TimingRoutine:Registry { public TimingRoutine() { Welcome(); } private void Welcome() { // 每2秒一次循环 Schedule<TaskJob>().ToRunNow().AndEvery(2).Seconds(); // 5秒后,只一次 Schedule<TaskJob>().ToRunOnceIn(5).Seconds(); //每天晚上21:15分执行 Schedule(() => Console.WriteLine("Timed Task - Will run every day at 9:15pm: " + DateTime.Now)).ToRunEvery(1).Days().At(21, 15); // 每个月的执行 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); //先执行第一个Job、再执行第二个Job;完成后等5秒继续循环 Schedule<TaskJob>().AndThen<TaskJob>().ToRunNow().AndEvery(5).Seconds(); //直接运行 Schedule(() => Console.Write("3, ")) .WithName("[welcome]") .AndThen(() => Console.Write("2, ")) .AndThen(() => Console.Write("1, ")) .AndThen(() => Console.WriteLine("Live!")); } } }
3.新建调用任务类继承IJob
using System; using System.IO; using FluentScheduler; namespace DemoProject2020 { public class TaskJob:IJob { void IJob.Execute() { var str = "循环每2秒执行一次;现在时间是:" + DateTime.Now.ToString(); System.IO.StreamWriter writer = null; try { //写入日志 string path= Server.MapPath("~/logs"); ; //不存在则创建错误日志文件夹 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += string.Format(@"{0}.txt", DateTime.Now.ToString("yyyy-MM-dd")); writer = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path); //判断文件是否存在,如果不存在则创建,存在则添加 writer.WriteLine(str); writer.WriteLine("********************************************************************************************"); } finally { if (writer != null) { writer.Close(); } } } } }
4.新建Global.asax,全局应用程序处理类
Global.asax添加注册定时程序
protected void Application_Start(object sender, EventArgs e) { //注册定时任务 JobManager.Initialize(new TimingRoutine()); }
补充:
Let's suppose it's 10:00 of a Monday morning and you want to start a job that runs every Monday at 14:00. Should the first run of your job be today or only on the next week Monday? If you want the former (not waiting for a whole week): 如果想每周一10点运行,那个你选择现在就开始你的任务还是下周一再进行执行,如果现在开始,而不是等一周后执行 // Every "zero" weeks Schedule<MyJob>().ToRunEvery(0).Weeks().On(DayOfWeek.Monday).At(14, 0); Or if you want the latter (making sure that at least one week has passed): 如果选择下周一执行,确保至少一周已经过去。 // Every "one" weeks Schedule<MyJob>().ToRunEvery(1).Weeks().On(DayOfWeek.Monday).At(14, 0);