【问题标题】:Quartz.NET Scheduler, initalization in each scheduler.Start()Quartz.NET Scheduler,在每个 scheduler.Start() 中初始化
【发布时间】:2015-05-18 16:53:14
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# quartz.net


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多