Quartz job设置属性参数,动态执行jar

动态调用jar,配置开始时间执行次数等.

被调度的任务类(利用反射机制调用指定jar):

package sy.quartz;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import sy.jar.loader.JarLoader;

public class MyQuartzJob implements Job {
	private static final Logger logger = Logger.getLogger(MyQuartzJob.class);

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		//获取参数
		JobDataMap jdm = context.getJobDetail().getJobDataMap();
		String path = jdm.getString("path");
		String c = jdm.getString("class");
		String m = jdm.getString("method");
		String p = jdm.getString("parameter");
		// String t = jdm.getString("types");
		path = path == null ? "" : path;
		c = c == null ? "" : c;
		m = m == null ? "" : m;
		p = p == null ? "" : p;
		// t = t == null ? "" : t;
		// String[] ts = t.split(",");
		try {
			JarLoader loader = JarLoader.getInstance();
			try {
				// 加载jar
				loader.addURL("jar:file:///" + path + "!/");
				// 加载类
				Class qc = Class.forName(c, true, loader);
				// 获取参数类型
				// Class[] classs = getTypes(ts);
				Method ms = null;
				//无参数则不设置参数
				if (p.length() == 0) {
					ms = qc.getDeclaredMethod(m, new Class<?>[] {});
					ms.invoke(qc.newInstance(), null);
				} else {
					ms = qc.getDeclaredMethod(m, Object[].class);
					ms.invoke(qc.newInstance(), p.split(","));
				}
				// Object[] objs = getValuesByType(p.split(","), classs);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			logger.error("path:" + path + "/class:" + c + "/method:" + m,
					e.getCause());
			e.printStackTrace();
		}

	}
}

数据存储类:

package sy.model.base;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

@Entity
@Table(name = "SYQUARTZ", schema = "")
@DynamicInsert(true)
@DynamicUpdate(true)
public class Syquartzs implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String id;
	private String executePath;
	private String executeClass;
	private String executeMethod;
	private String parameter;
	private Date startTime;
	private Date endTime;
	private int repeatCount;
	private long repeatInterval;

	public Syquartzs() {
		super();
	}

	public Syquartzs(String id, String executePath, String executeClass,
			String executeMethod, String parameter, Date startTime,
			Date endTime, int repeatCount, long repeatInterval) {
		super();
		this.id = id;
		this.executePath = executePath;
		this.executeClass = executeClass;
		this.executeMethod = executeMethod;
		this.parameter = parameter;
		this.startTime = startTime;
		this.endTime = endTime;
		this.repeatCount = repeatCount;
		this.repeatInterval = repeatInterval;
	}

	@Id
	@Column(name = "ID", unique = true, nullable = false, length = 36)
	public String getId() {
		if (!StringUtils.isBlank(this.id)) {
			return this.id;
		}
		return UUID.randomUUID().toString();
	}

	@Column(name = "EXECUTEPATH", nullable = false, length = 500)
	public String getExecutePath() {
		return executePath;
	}

	@Column(name = "EXECUTECLASS", length = 100)
	public String getExecuteClass() {
		return executeClass;
	}

	@Column(name = "EXECUTEMETHOD", length = 100)
	public String getExecuteMethod() {
		return executeMethod;
	}

	@Column(name = "PARAMETER", length = 500)
	public String getParameter() {
		return parameter;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "STARTTIME", length = 7)
	public Date getStartTime() {
		return startTime;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "ENDTIME", length = 7)
	public Date getEndTime() {
		return endTime;
	}

	@Column(name = "REPEATCOUNT", length = 10)
	public int getRepeatCount() {
		return repeatCount;
	}

	@Column(name = "REPEATINTERVAL", length = 20)
	public long getRepeatInterval() {
		return repeatInterval;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setExecutePath(String executePath) {
		this.executePath = executePath;
	}

	public void setExecuteClass(String executeClass) {
		this.executeClass = executeClass;
	}

	public void setExecuteMethod(String executeMethod) {
		this.executeMethod = executeMethod;
	}

	public void setParameter(String parameter) {
		this.parameter = parameter;
	}

	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	public void setRepeatCount(int repeatCount) {
		this.repeatCount = repeatCount;
	}

	public void setRepeatInterval(long repeatInterval) {
		this.repeatInterval = repeatInterval;
	}

}

测试方法:

package sy.quartz;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Service;

import sy.model.base.Syquartzs;

@Service
public class QuartzTest {

	public static void main(String[] args) {
		// 测试数据
		List<Syquartzs> qs = getQuartzsList();
		for (Syquartzs q : qs) {
			try {
				Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
				// 产生一个uuuid,避免job名重复
				String uid = UUID.randomUUID().toString();
				JobDetail job = new JobDetail("job" + uid,
						Scheduler.DEFAULT_GROUP, MyQuartzJob.class);
				// 设置job参数,调度执行时使用的是class.newInstance(),所以给对象设置值没意义
				JobDataMap jobDataMap = new JobDataMap();
				jobDataMap.put("path", q.getExecutePath());
				jobDataMap.put("class", q.getExecuteClass());
				jobDataMap.put("method", q.getExecuteMethod());
				jobDataMap.put("parameter", q.getParameter());
				job.setJobDataMap(jobDataMap);
				// 创建一个简单的规则
				SimpleTrigger trigger = new SimpleTrigger("trig" + uid,
						Scheduler.DEFAULT_GROUP, getDate(q.getStartTime()),
						getDate(q.getEndTime()), q.getRepeatCount(),
						q.getRepeatInterval());
				scheduler.scheduleJob(job, trigger);
				scheduler.start();
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 判断开始时间是否小于当前时间,小于当前时间则使用当前时间开始调用
	 * 
	 * @param dt
	 * @return
	 */
	private static Date getDate(Date dt) {
		if (dt != null && System.currentTimeMillis() > dt.getTime()) {
			return new Date();
		}
		return dt;
	}

	/**
	 * 获取测试数据
	 * 
	 * @return
	 */
	private static List<Syquartzs> getQuartzsList() {
		List<Syquartzs> qs = new ArrayList<Syquartzs>();
		Syquartzs q1 = new Syquartzs("1", "d:/test/test1.jar",
				"com.ly.test.Test", "add", "", new Date(), null, -1, 5000l);
		Syquartzs q2 = new Syquartzs("2", "d:/test/test1.jar",
				"com.ly.test.Test", "add", "", new Date(), null, -1, 10000l);
		Syquartzs q3 = new Syquartzs("3", "d:/test/test1.jar",
				"com.ly.test.Test", "add", "", new Date(), null, -1, 15000l);
		Syquartzs q4 = new Syquartzs("4", "d:/test/test1.jar",
				"com.ly.test.Test", "add", "", new Date(), null, 9, 60000l);
		qs.add(q1);
		qs.add(q2);
		qs.add(q3);
		qs.add(q4);
		return qs;
	}
}

好了,成功执行调度,本例使用的quartz-all-1.6.6.jar

审核通过后会附上下载地址,及测试项目下载地址.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值