定时任务-quartz

来源:互联网 发布:淘宝订单清洗期几天 编辑:程序博客网 时间:2024/05/22 00:08

一、jar 包 quartz 1.5.2.jar

       参考文档:http://www.blogjava.net/baoyaer/articles/155645.html

二、quartz实现

1.关键API

  • Scheduler - 与scheduler交互的主要API;
  • Job - 你通过scheduler执行任务,你的任务类需要实现的接口;
  • JobDetail - 定义Job的实例;
  • Trigger - 触发Job的执行;
  • Calendar - 日历指定时间点的集合,annualCalendar、monthlyCalendar、weeklyCalendar 对每年、每月、每周的定义
2.实现

    job代码实现


 

 <span style="background-color: rgb(255, 204, 51);">定时任务实现</span>

public static void main(String[] args) {try { //①创建一个JobDetail实例,指定Job JobDetail jobDetail = new JobDetail("job1", "jGroup1",UploadKeywordJob.class); //②通过CronTrigger定义调度规则:每天几点上传 CronTrigger cronTrigger = new CronTrigger("trigger1","tGroup1"); cronTrigger.setCronExpression("0 0 9 ? * *"); //③通过SchedulerFactory获取一个调度器实例 SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); //④ 注册并进行调度 scheduler.scheduleJob(jobDetail, cronTrigger); //⑤调度启动 scheduler.start();                //*         }catch (Exception se) {se.printStackTrace();}}

注:对于上面*号处让主线程睡眠原因没搞清楚,试过不加正常运行


使用Calendar,排除特定日期


①法定节日是以每年为周期的,所以使用AnnualCalendar

AnnualCalendar holidays 
= new AnnualCalendar();

②五一劳动节

Calendar laborDay 
= new GregorianCalendar();

laborDay.add(Calendar.MONTH,
5);

laborDay.add(Calendar.DATE,
1);

holidays.setDayExcluded(laborDay, 
true); ②-1:排除的日期,如果设置为false则为包含

③国庆节

Calendar nationalDay 
= new GregorianCalendar();

nationalDay.add(Calendar.MONTH,
10);

nationalDay.add(Calendar.DATE,
1);

holidays.setDayExcluded(nationalDay, 
true);③-1:排除该日期

scheduler.addCalendar(
"holidays", holidays, falsefalse);④向Scheduler注册日历


二、spring的定时任务的实现

 1.spring中的quartz

  1. <!-- Timer schedule -->  
  2.   
  3. <!--要调度的对象-->  
  4. <bean id="jobBean" class="net.xsbiz.common.MakeHtml" />  
  5. <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  6.     <property name="targetObject" ref="jobBean" />  
  7.     <property name="targetMethod" value="execute" />  
  8.     <!--将并发设置为false-->  
  9.     <property name="concurrent" value="false" />  
  10. </bean>  
  11.   
  12. <bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  13.         <property name="jobDetail" ref="jobDetail" />  
  14.                 <!--表达式,我的是每 30 执行一次-->  
  15.                <property name="cronExpression" value="0/30 * * * * ?" />  
  16. </bean>  
  17.   
  18. <!--  总管理类如果将lazy-init='false'那么容器启动就会执行调度程序   -->  
  19. <bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" >  
  20.         <property name="triggers">  
  21.             <list>  
  22.                 <!--作业调度器,list下可加入其他的调度器-->  
  23.             <ref bean="trigger" />  
  24.             </list>  
  25.     </property>  
  26. </bean>  

web.xml:

Xml代码  收藏代码
  1.  <!-- 设置Spring的监听,项目启动时候初始化 -->  
  2.  <listener>  
  3. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  4.  </listener>  
  5.  <!-- 指定Spring配置文件的路径 -->  
  6.  <context-param>   
  7.       <param-name>contextConfigLocation</param-name>   
  8.       <param-value>/WEB-INF/classes/applicationContext.xml</param-value>    
  9.  </context-param>   

 

MakeHtml.java :

Java代码  收藏代码
  1. //调用的类  
  2. public class MakeHtml {  
  3.     //调用的方法  
  4.     public void execute(){  
  5.         //需要做的事情  
  6.     }  
  7.   
  8.   
  9.          public static void main(String[] args) {  
  10.           
  11.            
  12.             System.out.println("----begin---");   
  13.   
  14.             ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");   
  15.   
  16.             // 如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化   
  17.   
  18.             context.getBean("startQuertz");   
  19.   
  20.             System.out.print("----end---");  
  21.             
  22.   
  23.     }  
  24.   
  25. }  
 2.spring中的spring-task

上节介绍了在Spring 中使用Quartz,本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种
形式,下面将分别介绍这两种方式。
第一种:配置文件方式
第一步:编写作业类
即普通的pojo,如下:
Java代码  
import org.springframework.stereotype.Service;  
@Service  
public class TaskJob {  
      
    public void job1() {  
        System.out.println(“任务进行中。。。”);  
    }  
}  
 第二步:在spring配置文件头中添加命名空间及描述
Xml代码  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:task="http://www.springframework.org/schema/task"   
    。。。。。。  
    xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
 第三步:spring配置文件中设置具体的任务
Xml代码  
 <task:scheduled-tasks>   
        <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>   
</task:scheduled-tasks>  
<context:component-scan base-package=" com.gy.mytask " />  
说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron及cronExpression表达式,具体写法这里不介绍了,详情见上篇文章附录。
这个配置不消多说了,spring扫描注解用的。
到这里配置就完成了,是不是很简单。
第二种:使用注解形式
也许我们不想每写一个任务类还要在xml文件中配置下,我们可以使用注解@Scheduled,我们看看源文件中该注解的定义:
Java代码  
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Scheduled  
{  
  public abstract String cron();  
  
  public abstract long fixedDelay();  
  
  public abstract long fixedRate();  
}  
 可以看出该注解有三个方法或者叫参数,分别表示的意思是:
cron:指定cron表达式
fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。
fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。
 
下面我来配置一下。
第一步:编写pojo
Java代码  
import org.springframework.scheduling.annotation.Scheduled;    
import org.springframework.stereotype.Component;  
  
@Component(“taskJob”)  
public class TaskJob {  
    @Scheduled(cron = "0 0 3 * * ?")  
    public void job1() {  
        System.out.println(“任务进行中。。。”);  
    }  
}  
 第二步:添加task相关的配置:
Xml代码  
 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
        http://www.springframework.org/schema/context   
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"  
    default-lazy-init="false">  
    <context:annotation-config />  
    <!—spring扫描注解的配置   -->  
    <context:component-scan base-package="com.gy.mytask" />  
      
<!—开启这个配置,spring才能识别@Scheduled注解   -->  
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
    <task:scheduler id="qbScheduler" pool-size="10"/>  
     
说明:理论上只需要加上这句配置就可以了,这些参数都不是必须的。
 
 Ok配置完毕,当然spring task还有很多参数,我就不一一解释了,具体参考xsd文档http://www.springframework.org/schema/task/spring-task-3.0.xsd。
三、最后补充


1 0