根据响应安排任务

时间:2012-04-16 09:14:39

标签: java spring scheduled-tasks quartz-scheduler

我正在尝试根据它的响应来安排任务。任务类似于:

public Date scheduledTask() {
    Date nextRun;
    // ...
    nextRun = something();
    // ...
    return nextRun;
}

如何确保在到达nextRun时再次调用相同的任务?

谢谢。

2 个答案:

答案 0 :(得分:0)

按照here提到的想法,然后您应该能够:

public class GuaranteeSchedule implements Trigger {

  private Future<?> resultForNextRun;
  private TaskScheduler scheduler;

  public void scheduledTask() {
    // 'this' is this trigger that is used by the scheduler 
    // and the method `nextExecutionTime` is automatically called by the scheduler
    resultForNextRun = scheduler.schedule(theTask, this);
    // theTask is the object that calls something()
  }

  // Implementing Trigger to add control dynamic execution time of this trigger
  @Override
  public Date nextExecutionTime(TriggerContext tc) {
    // make sure the result for the previous call is ready using the waiting feature of Future
    Object result = resultForNextRun.get();
    // Use tc or other stuff to calculate new schedule
    return new Date();
  }

}

其余的,您应该遵循参考文献中提到的配置。我相信这将解决依赖于前一个结果的下一次触发调用的问题。您可能还需要小心scheduledTask的第一次通话,以确保resultForNextRun != null

答案 1 :(得分:0)

使用标准的Quartz调度程序API非常简单。在Job计算nextRun时间内,创建一个定义为startAt()的触发器:

public class ScheduledJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        final Date nextRun = something();

        Trigger trigger = newTrigger().
                startAt(nextRun).
                forJob(context.getJobDetail()).
                build();

        context.getScheduler().scheduleJob(trigger);
    }

}

经过测试,就像魅力一样。