如何参数化这个方法并使其更加灵活?

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

我正在编写一种用 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'
c# type-parameter
1个回答
0
投票

如错误所示,

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
© www.soinside.com 2019 - 2024. All rights reserved.