我想安排一个作业以2秒的倍数运行,即2,4,8,16,32秒。第二次火灾应在第一次火灾完成两秒后发生,第三次火灾应在第二次火灾完成4秒后发生,依此类推。下一次射击是基于我们从前一次射击中获得的状态,根据这些状态,我们将决定是否需要触发下一次射击。谁能告诉我如何使用quartz scheduler来实现这一点?
如果我使用SimpleTrigger.withIntervalInSeconds(2),它每隔2秒运行一次作业,在每次触发时,时间间隔应该以2的倍数递增。
发布于 2017-09-11 00:23:06
也许您可以忘记尝试设置单个触发器,而是使用多个触发器。我的Java在这方面不是很好,所以这是伪代码:
delay = 2
repeat
TriggerOnceAfter(delay)
delay <- delay * 2
WaitUntilTriggered()
until (finished)我不确定如何实现WaitUntilTriggered()方法;您可能需要在触发的代码中添加一个信令标志,以便WaitUntilTriggered()查看。
这将给出2,4,8,...
发布于 2017-09-11 01:04:04
这是一个简化的实现,它将按照请求的时间表调用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();
}
}https://stackoverflow.com/questions/46140931
复制相似问题