Reputation: 39354
I have the following Quartz Job in a Net Core 6 project:
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);
}
}
And the Quartz configuration is the following:
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())
);
});
I need to make StrategyJob generic and apply it to different Strategies / Schedules:
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.
How to create a generic StrategyJob and apply it to different strategies / schedules?
Upvotes: 0
Views: 667
Reputation: 1449
You can add the strategy to the trigger's data. As long as you don't persist the scheduler in a database, you shouldn't be worried about the serialization of the trigger data.
var jobData = new Dictionary<string, object>
{
{ "Strategy", new FastStrategy(...) }
}
x.AddTrigger(y => y
.UsingJobData(new JobDataMap(jobData))
. ...
You'll need to provide your own implementation of 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);
}
}
Upvotes: 1