我想安排作业以2秒的倍数运行,即2,4,8,16,32秒。第二次火灾应在第一次火灾完成两秒后发生,第三次火灾应在第二次火灾完成4秒后发生,依此类推。下一场火灾是基于我们从之前的火力中获得的状态,根据该状态判断我们是否需要触发下一次火力。 有人可以告诉我如何使用石英调度程序来实现这一目标?
如果我使用SimpleTrigger.withIntervalInSeconds(2)它会在每2秒后运行一个作业,因为我希望时间间隔应该在每次发射时增加2的倍数。
答案 0 :(得分:0)
也许您可能忘记尝试设置单个触发器,但使用多个触发器。我的Java在这方面并不好,所以这是伪代码:
delay = 2
repeat
TriggerOnceAfter(delay)
delay <- delay * 2
WaitUntilTriggered()
until (finished)
我不确定如何实施WaitUntilTriggered()
方法;你需要在WaitUntilTriggered()
的触发代码中添加一个信令标志来查看。
这将延迟2,4,8,......
答案 1 :(得分:0)
这是一个简化的实现,它将按照请求的时间表调用Runnable
:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Tasker {
private int numberOfRuns; //how many times job executed
private int timeBetweenRuns;//seconds
Tasker(int numberOfRuns){
this.numberOfRuns = numberOfRuns;
timeBetweenRuns = 2;
execute();
}
private void execute() {
for (int counter = 0; counter < numberOfRuns ; counter++) {
CountDownLatch latch = new CountDownLatch(1);
Job job = new Job(latch, timeBetweenRuns);
job.run();
try {
latch.await();
TimeUnit.SECONDS.sleep(timeBetweenRuns);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
timeBetweenRuns *=2;
}
}
public static void main(String[] args){
new Tasker(5);
}
}
class Job implements Runnable {
private int seconds;
private CountDownLatch latch ;
Job(CountDownLatch latch , int seconds){
this.latch = latch;
this.seconds = seconds;
}
@Override
public void run() {
System.out.println("Job runs "+ seconds +" after previous one");
latch.countDown();
}
}