我最近开始使用quartz.net,但对线程安全性有疑问。
public class QuartzService
{
public async Task Start()
{
// construct a scheduler factory
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type","binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
// get a scheduler
IScheduler sched = await factory.GetScheduler();
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<TestJob>().StoreDurably()
.WithIdentity("myJob","jobGroup1")
.Build();
await sched.AddJob(job,true);
// Trigger the job to run now,and then every 40 seconds
ITrigger trigger1 = TriggerBuilder.Create()
.WithIdentity("myTrigger1","group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(5)
.RepeatForever())
.ForJob(job)
.Build();
// Trigger the job to run now,and then every 40 seconds
ITrigger trigger2 = TriggerBuilder.Create()
.WithIdentity("myTrigger2","group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(5)
.RepeatForever())
.ForJob(job)
.Build();
await sched.ScheduleJob(trigger1);
await sched.ScheduleJob(trigger2);
await sched.Start();
}
}
public class TestJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
}
}
在上面的示例中,我有一个包含两个触发器的作业。我的问题是两个触发器在运行时是否共享相同的作业实例?或每次触发器运行时,都会创建一个新的IJobDetail实例。我已经尝试阅读了quartz.net的文档,但由于将JobDetail实例与作业实例混合在一起,这非常令人困惑,我对这里的情况还不太清楚。