`

quartz定时任务使用

阅读更多

spring quartz(定时任务例子)
一.Quartz介绍
     Quartz是一个作业调度系统(a job scheduling system),负责在约定的时间到达时执行(或通知)其他软件控制。是一个Java的定时任务框架,使用它可以方便的实现计划任务,即在某个时间或每隔一定时间运行一个任务。Quartz的核心是Job/JobDetail,Trigger和Scheduler。

    1.Job/JobDetail
       Job/JobDetail=既要执行的任务,可以通过实现Job(interface)中的excute方法来指定任务的具体操作。 他描述了一个任务具体的信息,比如名称,组名等等。JobDetail对象是在Quartz的客户端(我们的程序)在Job被关联加入到Scheduler时创建的,JobDetail包含了Job的各种属性值和   JobDataMap,JobDataMap中存放了与之相关的Job类实例的状态信息。

    2.Trigger
       用于控制一组Job的触发,包裹SimmperTrigger和CronTrigger,后者支持一种描述触发事件和间隔的表达式语言。Quartz有个很好的想法就是分离了任务和任务执行的条件。Trigger就是控制任务执行条件的类,当Trigger认为执行条件满足的时刻,Trigger会通知相关的Job去执行。分离的好处是:
            1).你可以为某个Job关联多个Trigger,其中任何一个条件满足都可以触发job执行,这样可以完成一些组合的高级触发条件
            2).当Trigger失效后(比如:一个永远都不能满足的条件),你不必去声明一个新的job,代替的是你可以为job关联一个新的Trigger让job可以继续执行。
  
    3.Scheduler是控制和管理触发器的启动和终止。
       使用Scheduler前必须实例化Scheduler,需要由SchedulerFactory类来创建Scheduler,Factory的实例可以通过在JNDI存储中的Factory的序列化的方式获取,实例化Factory后直接使用该实例很容易。如下:
       public class WangyouQuartzListener extends QuartzInitializerListener {
            public  static  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            public WangyouQuartzListener() {
                       super();
            }

           public void contextInitialized(ServletContextEvent event) {
                    super.contextInitialized(event);
                    String factoryKey = event.getServletContext().getInitParameter("servlet-context-factory-key");
                     if (factoryKey == null) {
                               factoryKey = QUARTZ_FACTORY_KEY;
                      }
                      StdSchedulerFactory factory = (StdSchedulerFactory) event.getServletContext().getAttribute(factoryKey);

                   try {
                         QuartzScheduleHolder.getInstance().setScheduler(factory.getScheduler());
                       //per 2 hours add friends
                       Trigger trigger =  TriggerUtils.makeHourlyTrigger(24);
                       //Trigger trigger =  TriggerUtils.makeSecondlyTrigger(60);
                       trigger.setName(AddNewUserFriendJobDetail.JOB_NAME);
                      trigger.setStartTime(this.getBeforeAfterDate(1,-13));
                      QuartzScheduleHolder.getInstance().getScheduler().scheduleJob(new AddNewUserFriendJobDetail(),trigger);
                      //把job和Trigger关联,这样当Trigger认为应该触发的时候就会调用(实际上是Scheduler调用)job.execute方法了。

                      //per 3 day send mail and leave message
                      Trigger trigger2 =  TriggerUtils.makeHourlyTrigger(24*3);
                      trigger2.setStartTime(this.getBeforeAfterDate(1,-12));
                      trigger2.setName(LeaveMessageNewUserJobDetail.JOB_NAME);
                      QuartzScheduleHolder.getInstance().getScheduler().scheduleJob(new LeaveMessageNewUserJobDetail(),trigger2);

                       // per 6  recommend video
                      Trigger trigger3 =  TriggerUtils.makeHourlyTrigger(24*7);
                      trigger3.setName(RecommendVideoNewUserJobDetail.JOB_NAME);
                      trigger3.setStartTime(this.getBeforeAfterDate(2,-11));
                      QuartzScheduleHolder.getInstance().getScheduler().scheduleJob(new RecommendVideoNewUserJobDetail(),trigger3);

           
                         QuartzScheduleHolder.getInstance().getScheduler().start();
                   } catch (Exception e) {
                        e.printStackTrace();
                   }
              }

             public void contextDestroyed(ServletContextEvent event) {
                   super.contextDestroyed(event);
                     QuartzScheduleHolder.getInstance().setScheduler(null);
             }

              private Date getBeforeAfterDate( int day,int hour){
                       Calendar   cal   =   Calendar.getInstance();
                      cal.add(Calendar.DATE,day);
                     cal.add(Calendar.HOUR,hour);
                     return cal.getTime();
             }
           }
二。Spring Quartz
      Spring的scheduling。quartz包中对Quartz的框架进行封装,使得开发时不用写任何Quartz和Spring的代码就可以实现定时任务。Spring通过JobDetailBean,MethodInvokingJobDetailFactoryBean实现Job的定义,后者更加使用,只需指定要运行的类,和该类中运行的方法即可,Spring将自动生成符合Quartz要求的JobDetail。例如:
      1.jobDetail
         public class SayHelloJob {
   
                   private static  DateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                   private String message;

                   public String getMessage() {
                           return message;
                  }

                  public void setMessage(String message) {
                            this.message = message;
                 }

                 public void sayHello(){
                          Date date = new Date();
                         System.out.println(dateFormat.format(date)+" :"+this.getMessage() );
                 }
          }
       2.spring的配置文件:quartzbean.xml
           <?xml version="1.0" encoding="UTF-8"?>

           <beans xmlns="http://www.springframework.org/schema/beans"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
                    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

                    <bean name="sayHelloJob" class="com.fg114.takeout.job.SayHelloJob">
                              <property name="message" value="start .............." />
                   </bean>

                   <bean name="sayHelloDetailBean" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
                              <property name="targetObject" ref="sayHelloJob" />
                             <property name="targetMethod" value="sayHello"/>
                    </bean>

                   <bean name="simpleTriggerBean" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
                                  <!--这里定义定时任务的对象的位置-->
                            <property name="jobDetail" ref="sayHelloDetailBean"/>
                           <!--这里定义每六秒钟程序执行一次-->
                             <property name=""></property>
                            <property name="repeatInterval" value="6000"/>
                           <!--这里定义程序启动两秒钟后开始执行-->
                         <property name="startDelay" value="2000"/>
                    </bean>
                 <! --          启动任务    -->
                   <bean name="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
                         <property name="triggers">
                             <list>
                                  <ref bean="simpleTriggerBean"/>
                            </list>
                       </property>
                  </bean>
             </beans>
3.web.xml :
            加入
           <listener>
             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
           </listener>
       注意:common-collections.jar 版本布不能是2.1版本的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics