首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Quartz.NET Scheduler,每个scheduler.Start()中的化简

Quartz.NET Scheduler,每个scheduler.Start()中的化简
EN

Stack Overflow用户
提问于 2015-05-18 08:28:59
回答 1查看 1.3K关注 0票数 0

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

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

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

我尝试过的是:我定义了一个在RobotJob中返回RobotJob的抽象方法。我在MyRobotJob中实现了它,它返回了另一个类MyRobotRunner,实现了IJob。但是,如果在单独的类中这样做,就不能使用RobotJob中的日志方法。代码的简化版本如下所示:

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-18 08:34:06

您不需要每次添加工作时都调用scheduler.Start()。在调度器包装器上创建一个方法,它将添加您的作业,并且只启动您的调度程序一次。

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30298400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档