在你可以使用调度器之前,它需要被实例化(谁会猜到?)。 为此,您使用 ISchedulerFactory 的实现者。
一旦调度程序被实例化,它就可以启动、置于待机模式和关闭。 请注意,一旦调度程序关闭,如果不重新实例化,它就无法重新启动。 在调度程序启动之前,触发器不会触发(作业不会执行),也不会在它处于暂停状态时触发。
这是一个快速的代码片段,它实例化并启动一个调度程序,并安排一个作业执行:
使用 Quartz.NET
// construct a scheduler factory using defaults
StdSchedulerFactory factory = new StdSchedulerFactory();
// get a scheduler
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("myJob", "group1")
.Build();
// Trigger the job to run now, and then every 40 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(40)
.RepeatForever())
.Build();
await scheduler.ScheduleJob(job, trigger);
// You could also schedule multiple triggers for the same job with
// await scheduler.ScheduleJob(job, new List<ITrigger>() { trigger1, trigger2 }, replace: true);
使用 fluent API 配置调度程序
您还可以使用 SchedulerBuilder fluent API 以编程方式配置调度程序的不同方面。
var sched = await SchedulerBuilder.Create()
// default max concurrency is 10
.UseDefaultThreadPool(x => x.MaxConcurrency = 5)
// this is the default
// .WithMisfireThreshold(TimeSpan.FromSeconds(60))
.UsePersistentStore(x =>
{
// force job data map values to be considered as strings
// prevents nasty surprises if object is accidentally serialized and then
// serialization format breaks, defaults to false
x.UseProperties = true;
x.UseClustering();
x.UseSqlServer("my connection string");
// this requires Quartz.Serialization.Json NuGet package
x.UseJsonSerializer();
})
// job initialization plugin handles our xml reading, without it defaults are used
// requires Quartz.Plugins NuGet package
.UseXmlSchedulingConfiguration(x =>
{
x.Files = new[] { "~/quartz_jobs.xml" };
// this is the default
x.FailOnFileNotFound = true;
// this is not the default
x.FailOnSchedulingError = true;
})
.BuildScheduler();
await scheduler.Start();
如您所见,使用 Quartz.NET 相当简单。 在第 2 课中,我们将简要介绍作业和触发器,以便您更全面地理解这个示例。