1、新建项目
简单实例,新建一个控制台程序
2、Nuget安装Quartz
3、编写代码
using Quartz;
using Quartz.Impl;
using Quartz.Logging;
using System;
using System.IO;
using System.Threading.Tasks;
namespace QuartzDotNetDemo
{
class Program
{
static async Task Main(string[] args)
{
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
// 获取调度程序的实例
// 创建调度器工厂
StdSchedulerFactory factory = new StdSchedulerFactory();
// 创建调度器
IScheduler scheduler = await factory.GetScheduler();
// 启动
await scheduler.Start();
// 创建一个任务
IJobDetail job = JobBuilder.Create<HelloJob>().WithIdentity("job1", "group1").Build();
// 创建一个触发器
ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger1", "group1").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(10) // 间隔10秒执行一次
.RepeatForever()).Build();
// 将任务与出发器添加到调度器中
await scheduler.ScheduleJob(job, trigger);
// 延迟60秒后启动
await Task.Delay(TimeSpan.FromSeconds(60));
// 关闭
await scheduler.Shutdown();
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
}
}
/// <summary>
/// 增加日志记录
/// </summary>
public class ConsoleLogProvider: ILogProvider
{
public Logger GetLogger(string name)
{
return(level, func, exception, parameters) =>
{
if(level >= LogLevel.Info && func != null)
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
}
return true;
};
}
public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
throw new NotImplementedException();
}
public IDisposable OpenNestedContext(string message)
{
throw new NotImplementedException();
}
}
/// <summary>
/// 简单的测试
/// </summary>
public class HelloJob: IJob
{
public async Task Execute(IJobExecutionContext context)
{
// 输出对控制台的问候
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}
}
4、执行效果
5、相关链接
一个简单的实例,如有帮助,欢迎点赞关注收藏!
以上就是Quartz.NET 任务调度框架的demo实例的介绍,做此记录,如有帮助,欢迎点赞关注收藏!