Permalink
Browse files

[#13] Use a less hacky way to avoid double trigger for cron jobs

  • Loading branch information...
1 parent b43435e commit 5b2431daa9d0e4b3a4f31c03dc66f0b873388a1c @erwan erwan committed Apr 13, 2011
Showing with 13 additions and 13 deletions.
  1. +7 −4 framework/src/play/jobs/Job.java
  2. +6 −9 framework/src/play/jobs/JobsPlugin.java
@@ -1,12 +1,10 @@
package play.jobs;
+import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
-import com.jamonapi.Monitor;
-import com.jamonapi.MonitorFactory;
-
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.LazyLoader;
import play.Invoker;
@@ -15,11 +13,14 @@
import play.Play;
import play.exceptions.JavaExecutionException;
import play.exceptions.PlayException;
-import play.libs.Time;
import play.libs.F.Promise;
+import play.libs.Time;
import play.mvc.Http;
import play.utils.FakeRequestCreator;
+import com.jamonapi.Monitor;
+import com.jamonapi.MonitorFactory;
+
/**
* A job is an asynchronously executed unit of work
* @param <V> The job result type (if any)
@@ -34,6 +35,8 @@
protected boolean wasError = false;
protected Throwable lastException = null;
+ Date nextPlannedExecution = null;
+
@Override
public InvocationContext getInvocationContext() {
return new InvocationContext(invocationType, this.getClass().getAnnotations());
@@ -202,20 +202,17 @@ public void onApplicationStart() {
}
try {
Date now = new Date();
- Date nextInvalid;
- // Bug #13: to avoid clock problems, we don't set the next execution to less than
- // 5% of the interval between 2 executions
- long threshold = Time.cronInterval(cron) * 5 / 100;
cron = Expression.evaluate(cron, cron).toString();
CronExpression cronExp = new CronExpression(cron);
Date nextDate = cronExp.getNextValidTimeAfter(now);
- long delay = nextDate.getTime() - now.getTime();
- while (delay < threshold) {
- nextInvalid = cronExp.getNextInvalidTimeAfter(nextDate);
+ if (nextDate.equals(job.nextPlannedExecution)) {
+ // Bug #13: avoid running the job twice for the same time
+ // (happens when we end up running the job a few minutes before the planned time)
+ Date nextInvalid = cronExp.getNextInvalidTimeAfter(nextDate);
nextDate = cronExp.getNextValidTimeAfter(nextInvalid);
- delay = nextDate.getTime() - now.getTime();
}
- executor.schedule((Callable<V>)job, delay, TimeUnit.MILLISECONDS);
+ job.nextPlannedExecution = nextDate;
+ executor.schedule((Callable<V>)job, nextDate.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
job.executor = executor;
} catch (Exception ex) {
throw new UnexpectedException(ex);

0 comments on commit 5b2431d

Please sign in to comment.