我有几个机器人作业扩展到抽象RobotJob类,共享日志文件,配置,暂停/继续选项等。我正在尝试采用Quartz.NET来安排这些工作。我还试图通过最少的代码/结构修改来使其工作。然而,我有两个相互交织的问题:
1)在MyRobotJob中我需要一个无参数的构造函数,因为scheduler.Start()构造了一个新的MyRobotJob对象,但是我不想要一个无参数的构造函数。
2)由于scheduler.Start()创建了一个新的MyRobotJob,因此有一个由构造函数调用产生的无限循环。我知道这个设计是有问题的,我想知道如何修改它,以便只有一个MyRobotJob对象按照计划运行。
我尝试过的是:我定义了一个在RobotJob中返回RobotJob的抽象方法。我在MyRobotJob中实现了它,它返回了另一个类MyRobotRunner,实现了IJob。但是,如果在单独的类中这样做,就不能使用RobotJob中的日志方法。代码的简化版本如下所示:
public abstract class RobotJob
{
public string Cron { get; set; }
public string LogFile { get; set; }
public JobStatus Status { get; set; }
// Properties, helpers...
protected RobotJob(string name, string cron, string logFile = null)
{
this.Name = name;
this.LogFile = logFile;
this.Cron = cron;
InitQuartzScheduler();
}
private void InitQuartzScheduler()
{
scheduler = StdSchedulerFactory.GetDefaultScheduler();
IJobDetail job = JobBuilder.Create(this.GetType())
.WithIdentity(this.GetType().Name, "AJob")
.Build();
trigger = TriggerBuilder.Create()
.WithIdentity(this.GetType().Name, "ATrigger")
.StartNow()
.WithCronSchedule(Cron)
.Build();
scheduler.ScheduleJob(job, trigger);
scheduler.Start(); // At this part, infinite loop starts
}
}
[DisallowConcurrentExecution]
public class MyRobotJob : RobotJob, IJob
{
// I need a parameterless constructor here, to construct
public MyRobotJob()
: base("x", "cron", "logFile")
public MyRobotJob(string name, string cron, string logFile = null)
: base(name, cron, logFile)
{
}
public override void Execute(IJobExecutionContext context)
{
// DoStuff();
}
}发布于 2015-05-18 08:34:06
您不需要每次添加工作时都调用scheduler.Start()。在调度器包装器上创建一个方法,它将添加您的作业,并且只启动您的调度程序一次。
public class Scheduler : IScheduler
{
private readonly Quartz.IScheduler quartzScheduler;
public Scheduler()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
quartzScheduler = schedulerFactory.GetScheduler();
quartzScheduler.Start();
}
public void Stop()
{
quartzScheduler.Shutdown(false);
}
public void ScheduleRoboJob()
{
// your code here
quartzScheduler.ScheduleJob(job, trigger);
}https://stackoverflow.com/questions/30298400
复制相似问题