org.openkoala.koala.monitor.extend.BaseSchedulerBean.java Source code

Java tutorial

Introduction

Here is the source code for org.openkoala.koala.monitor.extend.BaseSchedulerBean.java

Source

/*
 * Copyright (c) openkoala 2011 All Rights Reserved
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.openkoala.koala.monitor.extend;

import java.util.Arrays;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.openkoala.koala.config.domain.SchedulerConfg;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 *     ??BaseSchedulerBean.java<br />
 *   
 * ??  <br />
 *  
 * 2012-2-13?11:04:13  <br />   
 * 
 * ?v 1.0<br />
 * 
 * ??Copyright (c) 2011 Csair All Rights Reserved<br />
 * 
 *     <a href="mailto:jiangwei@openkoala.com">vakin jiang</a><br />
 * 
 *  <br />
 *                   
 */
public abstract class BaseSchedulerBean {
    private static final Logger logger = LoggerFactory.getLogger(BaseSchedulerBean.class);

    protected String triggerName;//

    protected String schedulerName;//

    protected String cronExpression;

    protected Scheduler scheduler;

    @Inject
    @Named("km_transactionTemplate")
    protected TransactionTemplate transactionTemplate;

    @Inject
    @Named("km_repository")
    protected EntityRepository repository;

    protected EntityRepository getRepository() {
        if (repository == null) {
            repository = InstanceFactory.getInstance(EntityRepository.class, "km_repository");
        }
        return repository;
    }

    public void setRepository(EntityRepository repository) {
        this.repository = repository;
    }

    protected Scheduler getScheduler() {
        if (scheduler == null)
            scheduler = InstanceFactory.getInstance(Scheduler.class);
        return scheduler;
    }

    public void setTriggerName(String triggerName) {
        this.triggerName = triggerName;
    }

    public void setSchedulerName(String schedulerName) {
        this.schedulerName = schedulerName;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public void execute() {
        String latestConExpr = null;
        boolean runing = false;
        try {
            latestConExpr = checkExecutable();
            if (latestConExpr == null)
                return;
            updateExecutable(true);
            runing = true;
            //
            doJob();
            //??
            checkConExpr(latestConExpr);
        } catch (Exception e) {
            logger.error(schedulerName + "[" + triggerName + "]?", e);
        } finally {
            if (runing) {
                updateExecutable(false);
            }
        }
    }

    public void checkConExpr(String latestConExpr) {
        try {
            //check cronExpr valid
            CronTriggerImpl trigger = (CronTriggerImpl) getScheduler()
                    .getTrigger(new TriggerKey(triggerName, Scheduler.DEFAULT_GROUP));
            String originConExpression = trigger.getCronExpression();
            //?
            if (!originConExpression.equalsIgnoreCase(latestConExpr)) {
                logger.info("reset ConExpression[{}] To [{}] ", originConExpression, latestConExpr);
                trigger.setCronExpression(latestConExpr);
                getScheduler().rescheduleJob(new TriggerKey(triggerName, Scheduler.DEFAULT_GROUP), trigger);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * ???(????)<br>
     * generate by: vakin jiang
     *                    at 2012-2-13
     * @return
     */
    protected String checkExecutable() {
        try {
            SchedulerConfg scheduler = repository.get(SchedulerConfg.class, triggerName);
            if (scheduler == null)
                return cronExpression;
            if (!scheduler.isActive()) {
                if (logger.isDebugEnabled())
                    logger.debug(schedulerName + "[{}]?,", triggerName);
                return null;
            }
            if (scheduler.isRunning()) {
                int excInterval = getExcInterval();
                long actualInterval = getDiffMinutes(scheduler.getLastBeginRunTime(), new Date());
                if (actualInterval > excInterval) {
                    if (logger.isDebugEnabled())
                        logger.debug(schedulerName + "[{}][" + excInterval
                                + "],?[" + actualInterval + "]?",
                                triggerName);
                    cronExpression = scheduler.getCronExpr();
                    return cronExpression;
                }
                if (logger.isDebugEnabled())
                    logger.debug(schedulerName + "[{}],?",
                            triggerName);
                return null;
            }
            cronExpression = scheduler.getCronExpr();
        } catch (Exception e) {
        }
        return cronExpression;
    }

    /**
     * ??<br>
     * generate by: vakin jiang
     *                    at 2012-2-13
     * @param runing
     */
    @Transactional
    protected void updateExecutable(final boolean runing) {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                String hql = "";
                Object[] params = null;
                if (runing) {
                    hql = "update SchedulerConfg set running = ?,lastBeginRunTime = ? where triggerName = ?";
                    params = new Object[] { true, new Date(), triggerName };
                } else {
                    hql = "update SchedulerConfg set running = ? where triggerName = ?";
                    params = new Object[] { false, triggerName };
                }
                repository.createJpqlQuery(hql).setParameters(Arrays.asList(params)).executeUpdate();
                return null;
            }
        });
    }

    public void resumeTrigger() {
        try {
            getScheduler().resumeTrigger(new TriggerKey(triggerName, Scheduler.DEFAULT_GROUP));
            logger.info("???" + getScheduler().isStarted());
        } catch (SchedulerException e) {
            throw new RuntimeException("???" + e.getMessage());
        }
    }

    /**
     * ?<br>
     * generate by: vakin jiang
     *                    at 2012-12-6
     * @return
     */
    private int getExcInterval() {
        //
        return 60;
    }

    public void onStart() {
        if (StringUtils.isBlank(triggerName))
            return;
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                SchedulerConfg scheduler = getRepository().get(SchedulerConfg.class, triggerName);
                if (scheduler == null) {
                    scheduler = new SchedulerConfg(triggerName, schedulerName, cronExpression);
                }
                scheduler.setRunning(false);
                getRepository().save(scheduler);
                return null;
            }
        });

        logger.info("?" + schedulerName + "[{}]OK", triggerName);
    }

    @PreDestroy
    public void onStop() {
        updateExecutable(false);
    }

    /**
    * 
    * */
    public static long getDiffMinutes(Date d1, Date d2) {
        long between = Math.abs((d2.getTime() - d1.getTime()) / 1000);
        long min = between / 60;// ?
        return min;
    }

    public abstract void doJob() throws Exception;

}