通用 Quartz 作业应用于不同的 类 和时间表
Generic Quartz Job applied to different Classes and Schedules
我在 Net Core 6 项目中有以下 Quartz 作业:
public class StrategyJob : IJob {
private readonly Logger _logger;
private readonly Strategy _strategy;
public StrategyJob(Logger logger, Strategy strategy) {
_logger = logger;
_strategy = strategy;
}
public async Task Execute(IJobExecutionContext context) {
Result result = await strategy.Run();
if (result.Code == ResultCode.Error)
_logger.Error(result.ErrorMessage);
}
}
Quartz 配置如下:
services.AddQuartz(x => {
// Quartz configuration
x.AddJob<StrategyJob>(y => y
.WithIdentity("StrategyJob")
);
x.AddTrigger(y => y
.WithIdentity("Minute10OfEveryHour")
.ForJob("StrategyJob")
.WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())
);
});
我需要使 StrategyJob 通用并将其应用于不同的策略/计划:
Strategy fs = new FastStrategy(2, 4, 5); > Run it every second
Strategy ss = new SlowStrategy("xy", 2); > Run it every day
... More strategies, each with a schedule, but the job execution will be the same.
如何创建通用 StrategyJob 并将其应用于不同的策略/计划?
您可以将策略添加到触发器的数据中。只要您不将调度程序保存在数据库中,就不必担心触发器数据的序列化。
var jobData = new Dictionary<string, object>
{
{ "Strategy", new FastStrategy(...) }
}
x.AddTrigger(y => y
.UsingJobData(new JobDataMap(jobData))
. ...
您需要提供自己的 IJobFactory
实现
public class JobFactory : IJobFactory
{
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var strategy = (Strategy)bundle.JobDetail.JobDataMap.Get("Strategy");
return new StrategyJob(logger, strategy);
}
}
我在 Net Core 6 项目中有以下 Quartz 作业:
public class StrategyJob : IJob {
private readonly Logger _logger;
private readonly Strategy _strategy;
public StrategyJob(Logger logger, Strategy strategy) {
_logger = logger;
_strategy = strategy;
}
public async Task Execute(IJobExecutionContext context) {
Result result = await strategy.Run();
if (result.Code == ResultCode.Error)
_logger.Error(result.ErrorMessage);
}
}
Quartz 配置如下:
services.AddQuartz(x => {
// Quartz configuration
x.AddJob<StrategyJob>(y => y
.WithIdentity("StrategyJob")
);
x.AddTrigger(y => y
.WithIdentity("Minute10OfEveryHour")
.ForJob("StrategyJob")
.WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())
);
});
我需要使 StrategyJob 通用并将其应用于不同的策略/计划:
Strategy fs = new FastStrategy(2, 4, 5); > Run it every second
Strategy ss = new SlowStrategy("xy", 2); > Run it every day
... More strategies, each with a schedule, but the job execution will be the same.
如何创建通用 StrategyJob 并将其应用于不同的策略/计划?
您可以将策略添加到触发器的数据中。只要您不将调度程序保存在数据库中,就不必担心触发器数据的序列化。
var jobData = new Dictionary<string, object>
{
{ "Strategy", new FastStrategy(...) }
}
x.AddTrigger(y => y
.UsingJobData(new JobDataMap(jobData))
. ...
您需要提供自己的 IJobFactory
public class JobFactory : IJobFactory
{
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var strategy = (Strategy)bundle.JobDetail.JobDataMap.Get("Strategy");
return new StrategyJob(logger, strategy);
}
}