使用反射传递类作为输入
本文关键字:输入 反射 | 更新日期: 2023-09-27 18:16:53
我有一个函数,它创建一个Quartz作业并返回调度程序,如下所示:
public IScheduler ScheduleJob<T>(string jobName, string jobGroup, string triggerName, string triggerGroup, bool rerun, string cronSchedule = "default", string startTime = "default") where T : IJob
{
var scheduler = StdSchedulerFactory.GetDefaultScheduler();
var jobKey = new JobKey(jobName, jobGroup);
var job = JobBuilder.Create<T>()
.WithIdentity(jobKey)
.StoreDurably()
.Build();
var trigger = cronSchedule != "default" ? QuartzCreateCronTrigger(triggerName, triggerGroup, cronSchedule, rerun, startTime) : QuartzCreateTrigger(triggerName, triggerGroup);
scheduler.ScheduleJob(job, trigger);
return scheduler;
}
我有几个类,每个类都包含一个要调度和运行的作业。我有以下函数,它接受其中一个类的名称和一些附加信息,然后调度作业。这个函数调用上面的函数。
public static void CreateScheduler(bool rerun, string jobName, string jobType, string schedule, string startTime)
{
var job = (IJob) Activator.CreateInstance(Type.GetType("MyProject.Jobs." + jobType + "." + jobName + ", " + Assembly.GetExecutingAssembly().FullName.ToString()));
var scheduler =
new QuartzConstraints().ScheduleJob<job>(
jobName,
jobType,
jobName + "Trigger",
jobType,
rerun,
schedule,
startTime);
scheduler.Start();
}
问题是我在new QuartzConstraints().ScheduleJob<job>(...)
中得到一个错误,说"无法解析符号'job'"。ScheduleJob<T>
应该有T
为IJob
型,这是正确的。我不知道我做错了什么。
当我明确定义每个类时,代码可以工作,但是我想编写一个一般化的方法(CreateScheduler
)以适用于任何类。例如,这可以工作(其中ThisIsAJobClass
是实现IJob
的类):
var scheduler =
new QuartzConstraints().ScheduleJob<ThisIsAJobClass>(
"ThisIsAJobClass",
"JobGroup1",
"ThisIsAJobClassTrigger",
"JobGroup1",
true,
"0 0/1 * ? * MON-FRI",
"6:20 AM");
scheduler.Start();
你应该写new QuartzConstrainst().ScheduleJob<IJob>
,而不是.ScheduleJob<job>
。
job
不是一个类型,而你自己说ScheduleJob<T> should have T as type IJob
。
如果你想把var job
传递给ScheduleJob
,那么你应该这样定义SheduleJob
:
public IScheduler ScheduleJob<T>(
T job, // <-- add this
string jobName,
string jobGroup,
string triggerName,
string triggerGroup,
bool rerun,
string cronSchedule = "default",
string startTime = "default") where T : IJob
{
// code
}
,然后将job
传递给这个函数,如下所示:
public static void CreateScheduler(bool rerun, string jobName, string jobType, string schedule, string startTime)
{
var job = (IJob) Activator.CreateInstance(Type.GetType("MyProject.Jobs." + jobType + "." + jobName + ", " + Assembly.GetExecutingAssembly().FullName.ToString()));
var scheduler =
new QuartzConstraints().ScheduleJob<IJob>(
job // <-- add this
jobName,
jobType,
jobName + "Trigger",
jobType,
rerun,
schedule,
startTime);
scheduler.Start();
}