Reputation: 6467
I started using quartz.net recently and I have a question about thread safety.
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")}");
}
}
In the above example I have a job with two triggers. My question is do the two triggers share the same job instance when they run? Or every time a trigger runs a new instance of IJobDetail is created. I have tried to read the documentation of quartz.net but it is very confusing as it mixes JobDetail instances with job instance and it is not quite clear to me what is the situation here.
Upvotes: 0
Views: 1266
Reputation: 6884
With the default job factory SimpleJobFactory, a new object instance of given job type (CLR Type) is created for each job invocation. Job object instances in CLR sense are never shared by triggers by default.
However, one could create a custom job factory that could return singletons from, say, a inversion of control container.
There's also a distinction about job type to be made. JobDetails describe a type of of job and multiple triggers can point to same detail (and thus same Type). This leads to fact that there can be multiple jobs of same CLR type running at the same time if job doesn't have PreventConcurrentExecutionAttribute
applied. And to keep things interesting, PreventConcurrentExecutionAttribute
applies to job details, so two different job details (different job key) but same type could again run at the same time.
Upvotes: 1