Quartz.NET Scheduler,每个scheduler中的初始化.Start()

时间:2015-05-18 08:29:00

标签: c# quartz.net

我有几个机器人工作扩展到抽象RobotJob类,共享日志文件,配置,暂停/继续选项等...我尝试采用Quartz.NET来安排这些工作。我还尝试使用最少量的代码/结构修改来使其工作。但是,我有两个相互交织的问题:

1)我需要MyRobotJob中的无参数构造函数,因为scheduler.Start()构造了一个新的MyRobotJob对象,但我不想要一个无参数的构造函数。

2)由于scheduler.Start()创建了一个新的MyRobotJob,因此构造函数的调用会产生无限循环。我知道这个设计有问题,我想知道如何修改它,这样只会有一个MyRobotJob对象按照计划运行。

我尝试了什么:我定义了一个在IJob中返回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();
    }
}

1 个答案:

答案 0 :(得分:1)

每次添加作业时,您都不需要调用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);
}