到 Google 资讯主页   
EasyJF首页   资料   源码   软件    论坛   网站    
   使用帮助    
    该信息为本站MyRSS系统缓存内容,部分图片及附件有可能无法正常使用.easyjf.comwww.matrix.org.cn无关,不对该信息负责.通过http://www.matrix.org.cn//resource/article/43/43632_quartz_schedule_job.html访问该信息的原始内容.
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   
Web App使用Quartz实现java schedule job
作者:tyrone1979 来源:www.matrix.org.cn  发布时间:2006-02-22 17:51:38.937

关于Quartz
1 下载Quartz java包copy到WEB-INF/lib下

2 建立 scheduler初始化servlet

在web.xml里加入
    

<servlet> 
                  <servlet-name>Initializer</servlet-name>
              <servlet-class>
                    com.nova.colimas.web.action.StartupServlet
                </servlet-class>
                  <load-on-startup>1</load-on-startup>
   </servlet>


初始化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

 
相关文章
 
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   


EasyJF.com 2006 隐私政策 使用EasyJF前必读