| 1 |
|
|
| 2 |
|
|
| 3 |
|
|
| 4 |
|
|
| 5 |
|
|
| 6 |
|
|
| 7 |
|
|
| 8 |
|
|
| 9 |
|
|
| 10 |
|
|
| 11 |
|
|
| 12 |
|
|
| 13 |
|
|
| 14 |
|
|
| 15 |
|
|
| 16 |
|
|
| 17 |
|
package org.apache.camel.bam; |
| 18 |
|
|
| 19 |
|
import org.apache.camel.bam.model.TimerEvent; |
| 20 |
|
import org.apache.camel.impl.ServiceSupport; |
| 21 |
|
import org.apache.commons.logging.Log; |
| 22 |
|
import org.apache.commons.logging.LogFactory; |
| 23 |
|
import org.springframework.orm.jpa.JpaCallback; |
| 24 |
|
import org.springframework.orm.jpa.JpaTemplate; |
| 25 |
|
|
| 26 |
|
import javax.persistence.EntityManager; |
| 27 |
|
import javax.persistence.LockModeType; |
| 28 |
|
import javax.persistence.PersistenceException; |
| 29 |
|
import java.util.Date; |
| 30 |
|
import java.util.List; |
| 31 |
|
import java.util.concurrent.ExecutorService; |
| 32 |
|
|
| 33 |
|
|
| 34 |
|
|
| 35 |
|
|
| 36 |
0 |
public class TimerEngine extends ServiceSupport implements Runnable { |
| 37 |
0 |
private static final Log log = LogFactory.getLog(TimerEngine.class); |
| 38 |
|
|
| 39 |
|
private JpaTemplate template; |
| 40 |
|
private ExecutorService executor; |
| 41 |
0 |
private long windowMillis = 1000L; |
| 42 |
|
private Thread thread; |
| 43 |
|
|
| 44 |
|
public void run() { |
| 45 |
0 |
while (!isStopped()) { |
| 46 |
0 |
long nextPoll = System.currentTimeMillis() + windowMillis; |
| 47 |
|
|
| 48 |
0 |
Date window = new Date(nextPoll); |
| 49 |
0 |
List<TimerEvent> list = template.find("select x from " + TimerEvent.class.getName() + " where x.time < ?1 order by x.time", window); |
| 50 |
0 |
for (TimerEvent event : list) { |
| 51 |
0 |
fireEvent(event); |
| 52 |
0 |
} |
| 53 |
|
|
| 54 |
0 |
long timeToSleep = nextPoll - System.currentTimeMillis(); |
| 55 |
0 |
if (timeToSleep > 0) { |
| 56 |
0 |
log.debug("Sleeping for " + timeToSleep + " millis"); |
| 57 |
|
try { |
| 58 |
0 |
Thread.sleep(timeToSleep); |
| 59 |
|
} |
| 60 |
0 |
catch (InterruptedException e) { |
| 61 |
0 |
log.debug("Caught: " + e, e); |
| 62 |
0 |
} |
| 63 |
|
} |
| 64 |
0 |
} |
| 65 |
0 |
} |
| 66 |
|
|
| 67 |
|
protected void fireEvent(final TimerEvent event) { |
| 68 |
|
|
| 69 |
|
|
| 70 |
0 |
template.execute(new JpaCallback() { |
| 71 |
0 |
public Object doInJpa(EntityManager entityManager) throws PersistenceException { |
| 72 |
0 |
entityManager.lock(event, LockModeType.WRITE); |
| 73 |
0 |
event.fire(); |
| 74 |
0 |
entityManager.remove(event); |
| 75 |
0 |
return null; |
| 76 |
|
} |
| 77 |
|
}); |
| 78 |
|
|
| 79 |
0 |
} |
| 80 |
|
|
| 81 |
|
protected void doStart() throws Exception { |
| 82 |
0 |
thread = new Thread(this, "TimerEngine"); |
| 83 |
0 |
thread.start(); |
| 84 |
0 |
} |
| 85 |
|
|
| 86 |
|
protected void doStop() throws Exception { |
| 87 |
0 |
if (thread != null) { |
| 88 |
0 |
thread = null; |
| 89 |
|
} |
| 90 |
0 |
} |
| 91 |
|
} |