001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.bam;
018    
019    import org.apache.camel.bam.model.TimerEvent;
020    import org.apache.camel.impl.ServiceSupport;
021    import org.apache.commons.logging.Log;
022    import org.apache.commons.logging.LogFactory;
023    import org.springframework.orm.jpa.JpaCallback;
024    import org.springframework.orm.jpa.JpaTemplate;
025    
026    import javax.persistence.EntityManager;
027    import javax.persistence.LockModeType;
028    import javax.persistence.PersistenceException;
029    import java.util.Date;
030    import java.util.List;
031    import java.util.concurrent.ExecutorService;
032    
033    /**
034     * @version $Revision: $
035     */
036    public class TimerEngine extends ServiceSupport implements Runnable {
037        private static final Log log = LogFactory.getLog(TimerEngine.class);
038    
039        private JpaTemplate template;
040        private ExecutorService executor;
041        private long windowMillis = 1000L;
042        private Thread thread;
043    
044        public void run() {
045            while (!isStopped()) {
046                long nextPoll = System.currentTimeMillis() + windowMillis;
047    
048                Date window = new Date(nextPoll);
049                List<TimerEvent> list = template.find("select x from " + TimerEvent.class.getName() + " where x.time < ?1 order by x.time", window);
050                for (TimerEvent event : list) {
051                    fireEvent(event);
052                }
053    
054                long timeToSleep = nextPoll - System.currentTimeMillis();
055                if (timeToSleep > 0) {
056                    log.debug("Sleeping for " + timeToSleep + " millis");
057                    try {
058                        Thread.sleep(timeToSleep);
059                    }
060                    catch (InterruptedException e) {
061                        log.debug("Caught: " + e, e);
062                    }
063                }
064            }
065        }
066    
067        protected void fireEvent(final TimerEvent event) {
068            // lets try lock the object first
069    
070            template.execute(new JpaCallback() {
071                public Object doInJpa(EntityManager entityManager) throws PersistenceException {
072                    entityManager.lock(event, LockModeType.WRITE);
073                    event.fire();
074                    entityManager.remove(event);
075                    return null;
076                }
077            });
078    
079        }
080    
081        protected void doStart() throws Exception {
082            thread = new Thread(this, "TimerEngine");
083            thread.start();
084        }
085    
086        protected void doStop() throws Exception {
087            if (thread != null) {
088                thread = null;
089            }
090        }
091    }