关于Quartz
1 下载Quartz java包copy到WEB-INF/lib下
2 建立 scheduler初始化servlet
在web.xml里加入
Initializer
com.nova.colimas.web.action.StartupServlet
1
初始化servlet代码如下:
public class StartupServlet extends HttpServlet {
public void init(ServletConfig cfg) throws
javax.servlet.ServletException {
initScheduler(cfg);
return;
}
protected void initScheduler(ServletConfig cfg){
logger.info("Quartz Init Servlet loaded, initializing Scheduler...");
// Start now
try{
// Create an default instance of the Scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//将scheduler存入serlvet上下文。 cfg.getServletContext().setAttribute(Constants.SCHEDULER_KEY,scheduler);
}catch(Exception e){
logger.error("Quartz Init Servlet failed");
}
}
}
3 程序配置一个schedule job
/**
* @author tyrone
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class BatchEditAction extends Action implements PrivilegedAction {
private static Logger logger = null;
private Scheduler scheduler=null;
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception{
ActionMessages errors=new ActionMessages();
logger = Logger.getLogger(this.getClass());
//获得Servlet上下文
ServletContext ctx = request.getSession().getServletContext();
//获得scheduler对象
scheduler=(Scheduler)ctx.getAttribute(Constants.SCHEDULER_KEY);
//根据form属性建立job
createJob(form);
try{
logger.info("Scheduler starting up...");
//启动scheduler。
scheduler.start();
}catch(Exception e){
logger.error("scheduler get error");
}
return mapping.findForward("success");
}
/**
* create a job based on form info.
* @param form
* @return
*/
protected void createJob(ActionForm form) throws Exception{
BatchInfoForm batchinfo=(BatchInfoForm)form;
String classname=batchinfo.getFile();
SimpleTrigger sTrigger=null;
JobDetail jobDetail=null;
Calendar cal=null;
//如果是一天一次的job
if (batchinfo.getFrequency().equalsIgnoreCase("onceDaily")){
logger.info("Batch run OnceDaily");
cal = new AnnualCalendar();
//Add Calendar to the Scheduler
/*
* Setup a trigger to start firing now, with a null end date/time,
* repeat forever and have (hour*60+ minute)*60000 ms between each firing.
*/
//开始时间:11:45
String[] time=batchinfo.getDailyStartTime().split(":");
java.util.Calendar rightNow = java.util.Calendar.getInstance();
rightNow.set(java.util.Calendar.HOUR_OF_DAY,new Integer(time[0]).intValue());
rightNow.set(java.util.Calendar.MINUTE,new Integer(time[1]).intValue());
//间隔24小时
long repeatInterval=24*60*60000;
sTrigger = new SimpleTrigger("Trigger",
Scheduler.DEFAULT_GROUP, rightNow.getTime(), null,
SimpleTrigger.REPEAT_INDEFINITELY, repeatInterval);
}
}
// Trigger 关联一个Calendar, batchinfo.getName()唯一表示一个Calendar
sTrigger.setCalendarName(batchinfo.getName());
scheduler.addCalendar(batchinfo.getName(), cal, true, true);
try{
//job类名为com.nova.colimas.job.Test
jobDetail = new JobDetail(classname,
Scheduler.DEFAULT_GROUP, Class.forName(classname));
//job关联一个Trigger,加入scheduler
scheduler.scheduleJob(jobDetail, sTrigger);
}catch(ClassNotFoundException ex){
logger.error(ex);
throw new Exception();
}
return ;
}
}
4 Job代码,job必须继承org.quartz.Job
package com.nova.colimas.job;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class Test implements Job {
private static Logger logger = null;
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// 定时运行。
logger = Logger.getLogger(this.getClass());
logger.info("test job is running");
}
}
5 运行结果
[framework] 2005-08-23 11:45:29,440 - com.nova.colimas.job.Test -215700 [DefaultQuartzScheduler_Worker-0] INFO com.nova.colimas.job.Test - test job is running
Trackback: