我正在尝试使用C#在Quartz.NET和Topshelf上运行多个作业。
HostFactory.Run(c =>
{
c.ScheduleQuartzJobAsService(q =>
q.WithJob(() => JobBuilder.Create<TypeA>().Build())
.AddTrigger(() => TriggerBuilder.Create().WithSimpleSchedule(builder => builder.WithIntervalInSeconds(ConfigurationSettings.AppFrequencyInSeconds).RepeatForever()).Build())
).StartAutomatically().
ScheduleQuartzJobAsService(r =>
r.WithJob(() => JobBuilder.Create<TypeB>().Build())
.AddTrigger(() => TriggerBuilder.Create().WithSimpleSchedule(builder => builder.
WithIntervalInSeconds(ConfigurationSettings.AppFrequencyInSeconds).RepeatForever()).Build())
).StartAutomatically();
c.StartAutomatically();
c.SetServiceName("ServiceName");
});
使用上面的代码,只执行TypeB中的execute方法。我也尝试过:
HostFactory.Run(c =>
{
c.ScheduleQuartzJobAsService(q =>
q.WithJob(() => JobBuilder.Create<TypeA>().Build())
.AddTrigger(() => TriggerBuilder.Create().WithSimpleSchedule(builder => builder.
WithIntervalInSeconds(ConfigurationSettings.AppFrequencyInSeconds).RepeatForever()).Build())
).StartAutomatically();
c.StartAutomatically();
c.SetServiceName("Service1");
c.ScheduleQuartzJobAsService(r =>
r.WithJob(() => JobBuilder.Create<TypeB>().Build())
.AddTrigger(() => TriggerBuilder.Create().WithSimpleSchedule(builder => builder.
WithIntervalInSeconds(ConfigurationSettings.AppFrequencyInSeconds).RepeatForever()).Build())
).StartAutomatically();
c.StartAutomatically();
c.SetServiceName("Service2");
});
使用此代码,仅调用TypeB中的execute方法。我的类TypeA和TypeB都有&#39; Execute&#39;作为每个类的入口点的方法(如果它们自己是作业的一部分,则会被调用)。似乎第二个服务代码是总是被调用的服务代码 - 如果我交换这两个ScheduleQuartzJobAsService调用的顺序,它总是在第二个调用中执行的类。
如何编写HostFactory.Run方法,以便同时执行这两个作业?
答案 0 :(得分:13)
HostFactory.Run(c =>
{
c.Service<ContainerService>(s =>
{
s.ConstructUsing(name => new ContainerService());
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
s.ScheduleQuartzJob<ContainerService>(q =>
q.WithJob(() =>
JobBuilder.Create<TypeA>().Build())
.AddTrigger(() =>
TriggerBuilder.Create()
.WithSimpleSchedule(builder => builder
.WithIntervalInSeconds(20)
.RepeatForever())
.Build())
);
s.ScheduleQuartzJob<ContainerService>(q =>
q.WithJob(() =>
JobBuilder.Create<TypeB>().Build())
.AddTrigger(() =>
TriggerBuilder.Create()
.WithSimpleSchedule(builder => builder
.WithIntervalInSeconds(60)
.RepeatForever())
.Build())
);
});
});
...
public class ContainerService
{
public bool Start()
{
return true;
}
public bool Stop()
{
return true;
}
}
我的问题是我混淆了服务和工作类的概念。我一介绍ContainerService
Start()
和Stop()
bool方法返回true,我就致电ScheduleQuartzJob
而不是ScheduleQuartzJobAsService
,上述代码对我有效我的TypeA
和TypeB
已经实施IJob
。