我正在编写一种用 C# 创建 Quartz 调度作业的方法。目前看起来是这样的。
private async Task BuildJobs(int startHour, int endHour, int intervalOffsetSeconds = 0)
{
try
{
var job = JobBuilder.Create<RepostTransactionsJob>()
.WithIdentity(nameof(RepostTransactionsJob), TriggerGroup)
.WithDescription("Reposting transactions")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity(string.Concat(nameof(RepostTransactionsJob), "-trigger"), TriggerGroup)
.WithSchedule(CronScheduleBuilder.CronSchedule(string.Format("{2:ss} {2:mm} {0}-{1} ? * * *", startHour, endHour, TimeSpan.FromSeconds(intervalOffsetSeconds))))
.Build();
await this.scheduler.ScheduleJob(job, trigger);
}
catch (Exception ex)
{
this.logger.LogToLocal(ex.Message);
}
}
但是,我想参数化
RepostTransactionsJob
部分,但我很挣扎。我已尝试以下操作,但返回构建错误。
尝试:
private async Task BuildJobs<T>(int startHour, int endHour, int intervalOffsetSeconds = 0) where T : class
{
try
{
var jobName = typeof(T).Name;
var job = JobBuilder.Create<T>()
.WithIdentity(jobName, TriggerGroup)
.WithDescription("Reposting transactions")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity(string.Concat(jobName, "-trigger"), TriggerGroup)
.WithSchedule(CronScheduleBuilder.CronSchedule(string.Format("{2:ss} {2:mm} {0}-{1} ? * * *", startHour, endHour, TimeSpan.FromSeconds(intervalOffsetSeconds))))
.Build();
await this.scheduler.ScheduleJob(job, trigger);
}
catch (Exception ex)
{
this.logger.LogToLocal(ex.Message);
}
}
构建错误:
The type 'T' cannot be used as a type parameter 'T' in the generic type or method 'JobBuilder.Create<T>()' There is no implicit reference conversion from 'T' to 'Quartz.IJob'
JobBuilderCreate
有一个IJob
约束:
public static JobBuilder Create<T>()
where T : IJob
因此,您的方法需要同样的约束。
private async Task BuildJobs<T>(int startHour, int endHour, int intervalOffsetSeconds = 0) where T : IJob