Quartz.NET运行Job Self-Reschedule?

时间:2014-07-09 14:00:52

标签: c#-4.0 scheduled-tasks quartz.net

我已经完全以编程方式创建了Quartz.NET作业(没有配置文件等)。它按计划运行很好。使用cron字符串初始化作业,每5分钟运行一次。我希望工作能够根据环境改变自己的时间表(例如,随着时间的推移会发生错误,因此cron应该更改为30分钟)。

我正在尝试确定要在

中写什么
protected override void ExecuteInternal( IJobExecutionContext context )

方法所以工作"自我改变"。我是否在context.Scheduler属性中设置了一些内容?我是否必须去调度程序本身并终止该作业并重新创建它(虽然听起来有点笨拙)?

所有的想法都表示赞赏,谢谢。

3 个答案:

答案 0 :(得分:5)

虽然我没有使用Quartz.NET,但我在Java项目中使用了Quartz,我认为它们是相似的。我已经实现了类似于您描述的解决方案。在executeInteral方法中,您可以访问jobexecution上下文。基本上它涉及创建一个新的触发器,然后重新安排工作(rescheduleJob)。因此,当出现这种情况时,你会做类似的事情:

protected void ExecuteInternal( IJobExecutionContext context ) {
  // ... some code
  if (the_condition) {
     // figure out startTime
     // figure out endTime
     // figure out repeat time
     // figoure out repeatInterval
     Trigger trigger = new SimpleTrigger("OurNewTrigger","GROUP_NAME", context.getJobDetail().getName(),context.getJobDetail().getGroup(), startTime, endTime,repeatTime,repeatInterval);
     context.getScheduler().rescheduleJob("OurNewTrigger","GROUP_NAME",trigger);
  }
  // ... some more code
}

沿着这些方向。希望这会有所帮助。

答案 1 :(得分:3)

我希望在最后一次运行后5到25分钟之间的随机时间范围内运行该作业,使用this answer(来自@skarist)并对其进行一些更改并使用{{3}我解决了我的问题:

public class YourJob : IJob

{
  public void Execute(IJobExecutionContext context)
  {

    //write your execution code


    //reschedule code after execution code:
     var random = new Random();
     var num = random.Next(5,25);
     var date = DateTime.Now;
     var hour = date.AddMinutes(num).Hour;
     var min = date.AddMinutes(num).Minute;

     ITrigger trigger = TriggerBuilder.Create()
        .WithIdentity(context.Trigger.Key.Name)
        .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(hour, min))
        .StartAt(DateTime.Now)
        .WithPriority(1)
        .Build();

    IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
    scheduler.RescheduleJob(new TriggerKey(context.Trigger.Key.Name), trigger);

    }
}

答案 2 :(得分:2)

skarist让我走上正轨。包括我在这里发现的下一个孩子的发现。

protected override void ExecuteInternal( IJobExecutionContext jobContext )
{
// ... do work...
var tnew = new CronTriggerImpl( #nameofcurrentlyrunningjob# )
{
CronExpressionString = "my new cron string is here" ,
TimeZone = TimeZoneInfo.Utc
};
var jobNew = new JobDetailImpl( #nameofcurrentlyrunningjob# , typeof( CurrentJobType ) );
jobContext.Scheduler.RescheduleJob( new TriggerKey( #nameofcurrentlyrunningjob# ) , tnew );
}

我还在课程中添加了[DisallowConcurrentExecution]属性,但这并不直接相关。