Quartz.net多线程和线程安全

问题描述 投票:0回答:1

我最近开始使用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实例与作业实例混合在一起,这非常令人困惑,我对这里的情况还不太清楚。

c# .net .net-core quartz-scheduler quartz.net
1个回答
0
投票

使用默认作业工厂,将为每次调用触发器创建一个新的作业实例。可以创建一个可以从一个容器中返回单例的作业工厂。

如果作业不具有PreventConcurrentExecution属性,则可以同时运行两个作业实例。

© www.soinside.com 2019 - 2024. All rights reserved.