文章标签 ‘定时任务’
2014三月5

Nutz:结合quartz-2.2.1实现定时任务

StartSetup 项目启动时新建线程:

package com.hits.core;


import com.hits.modules.cms.task.LoadTask;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;

import com.hits.common.config.Globals;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 类描述: 创建人:Wizzer 联系方式:www.wizzer.cn 创建时间:2013-11-26 下午2:11:13
 */
public class StartSetup implements Setup {
    private final static Log log = Logs.get();

    @Override
    public void destroy(NutConfig config) {

    }

    @Override
    public void init(NutConfig config) {
        try {
            //初始化Quartz任务
            Globals.SCHEDULER = StdSchedulerFactory.getDefaultScheduler();
            new Thread(config.getIoc().get(LoadTask.class)).start();
        } catch (SchedulerException e) {
            log.error(e);
        } catch (Exception e) {
            log.error(e);
        }
    }

}
LoadTask.java 从任务表中加载任务,定时执行类方法:
package com.hits.modules.cms.task;

import com.hits.common.action.BaseAction;
import com.hits.common.config.Globals;
import com.hits.modules.cms.task.bean.Cms_task;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.integration.quartz.NutQuartzJobFactory;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.*;

/**
 * Created by Wizzer on 14-3-4.
 */
@IocBean
public class LoadTask extends BaseAction implements Runnable {
    @Inject
    protected Dao dao;
    private final static Log log = Logs.get();

    public void run() {
        List<Cms_task> tasks = daoCtl.list(dao, Cms_task.class, Cnd.where("is_enable", "=", 0));
        Globals.SCHEDULER.setJobFactory(new NutQuartzJobFactory());
        for (int i = 0; i < tasks.size(); i++) {
            Cms_task task = tasks.get(i);
            try {
                Map<String, String> map = new HashMap<String, String>();
                if (task.getTask_type() == 2 || task.getTask_type() == 3) {
                    map.put("site_id", task.getSite_id());
                    map.put("channel_id", task.getParam_value());
                } else if (task.getTask_type() == 1) {
                    map.put("site_id", task.getSite_id());
                }
                JobBuilder jobBuilder = JobBuilder.newJob(getClassByTask(task.getJob_class()));
                jobBuilder.setJobData(getJobDataMap(map));
                TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
                if (StringUtils.isNotBlank(task.getTask_code())) {
                    jobBuilder.withIdentity(task.getTask_code(), Scheduler.DEFAULT_GROUP);
                    triggerBuilder.withIdentity(task.getTask_code(), Scheduler.DEFAULT_GROUP);
                } else {
                    UUID uuid = UUID.randomUUID();
                    jobBuilder.withIdentity(uuid.toString(), Scheduler.DEFAULT_GROUP);
                    triggerBuilder.withIdentity(uuid.toString(), Scheduler.DEFAULT_GROUP);
                    task.setTask_code(uuid.toString());
                    daoCtl.update(dao, task);
                }
                triggerBuilder.withSchedule(getCronScheduleBuilder(getCronExpressionFromDB(task)));
                //调度任务
                
                Globals.SCHEDULER.scheduleJob(jobBuilder.build(), triggerBuilder.build());
                
            } catch (SchedulerException e) {
                log.error(e);
            } catch (ClassNotFoundException e) {
                log.error(e);
            } catch (Exception e) {
                log.error(e);
            }
        }
        if(tasks.size()>0){
            Globals.SCHEDULER.start();
        }
        

    }

    public static CronScheduleBuilder getCronScheduleBuilder(String cronExpression) {
        return CronScheduleBuilder.cronSchedule(cronExpression);
    }
    public String getCronExpressionFromDB(Cms_task task) {
        if (task.getExecycle() == 2) {
            return task.getCron_expression();
        } else {
            int execycle = task.getTask_interval_unit();
            String excep = "";
            if (execycle == 5) {//月
                excep = "0  " + task.getMinute() + " " + task.getHour() + " " + task.getDay_of_month() + " * ?";
            } else if (execycle == 4) {//周
                excep = "0  " + task.getMinute() + " " + task.getHour() + " " + " ? " + " * " + task.getDay_of_week();
            } else if (execycle == 3) {//日
                excep = "0  " + task.getMinute() + " " + task.getHour() + " " + " * * ?";
            } else if (execycle == 2) {//时
                excep = "0 0 */" + task.getInterval_hour() + " * * ?";
            } else if (execycle == 1) {//分
                excep = "0  */" + task.getInterval_minute() + " * * * ?";
            }
            return excep;
        }
    }

    /**
     * @param params 任务参数
     * @return
     */
    private JobDataMap getJobDataMap(Map<String, String> params) {
        JobDataMap jdm = new JobDataMap();
        Set<String> keySet = params.keySet();
        Iterator<String> it = keySet.iterator();
        while (it.hasNext()) {
            String key = it.next();
            jdm.put(key, params.get(key));
        }
        return jdm;
    }

    /**
     * @param taskClassName 任务执行类名
     * @return
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    private Class getClassByTask(String taskClassName) throws ClassNotFoundException {
        return Class.forName(taskClassName);
    }
}
quartz-2.2.1 配置文件:
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
# 跳过版本检查 #
org.quartz.scheduler.skipUpdateCheck=true
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
# 用NutIoc接管Quartz的JobFactory,实现用户需要的注入功能 #
org.quartz.scheduler.jobFactory.class=org.nutz.integration.quartz.NutQuartzJobFactory

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

org.quartz.jobStore.misfireThreshold = 60000
# 使用内存JobStore #
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

NutQuartzJobFactory.java 下载地址:

https://github.com/nutzam/nutzmore/blob/master/src/org/nutz/integration/quartz/NutQuartzJobFactory.java