我正在尝试根据它的响应来安排一个任务。该任务类似于:
public Date scheduledTask() {
Date nextRun;
// ...
nextRun = something();
// ...
return nextRun;
}如何确保在到达nextRun时再次调用同一任务
谢谢。
发布于 2012-04-17 03:55:12
使用标准的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);
}
}经过测试,效果很好。
发布于 2012-04-17 03:19:54
遵循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。
https://stackoverflow.com/questions/10171446
复制相似问题