任务调度-Quartz

Spring中Quartz的配置

jar下载地址

Quartz百度百科

Quartz是一个强大的企业级任务调度框架,Spring中继承并简化了Quartz,下面就看看在Spring中怎样配置Quartz:
首先我们来写一个被调度的类:

package com.kay.quartz;
public class QuartzJob
{

    public void work()
    {
    System.out.println("Quartz的任务调度!!!");
    }
}

Spring的配置文件:

说明:  首先我们需要配置一个Job,这里有两种方式:一种是为Job创建一个独立的JobClass,然后使用Spring的JobDetailBean配置该Job;另一种是使用MethodInvokingJobDetailFactoryBean指定一个方法,不需要一个单独的JobClass,它需要设置“targetObject”和“targetMethod”,则Trigger触发该Job的时候,目标方法会被调用。这里把“concurrent”设置为“false”,这被调用的方法不会在新线程里运行,而是顺序执行。接下来我们配置了一个名为“settlementTrigger”的Cron触发器,它定义了settlementJob合适被调用。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>   
        <!-- 要调用的工作类 -->
        <bean id="quartzJob" class="com.kay.quartz.QuartzJob"></bean>
        <!-- 定义调用对象和调用对象的方法 -->
        <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <!-- 声明调用的类 -->
            <property name="targetObject">
                <ref bean="quartzJob"/>
            </property>
            <!-- 声明调用类中的方法 -->
            <property name="targetMethod">
                <value>work</value>
            </property>
        </bean>
        <!-- 定义触发时间 -->
        <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
            <property name="jobDetail">
                <ref bean="jobtask"/>
            </property>
            <!-- cron表达式 :具体声明处于什么时间,触发此调度的类-->
            <property name="cronExpression">
                <value>10,15,20,25,30,35,40,45,50,55 * * * * ?</value>
            </property>
        </bean>
        <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序  -->
        <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
                    <ref bean="doTime"/>
                </list>
            </property>
        </bean>
   
</beans>

测试程序:

package com.kay.quartz;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest
{

    /**
     * @param  args
     */
    public static void main(String[] args)
    {
        System.out.println("Test start.");
        ApplicationContext context = new ClassPathXmlApplicationContext("quartz-config.xml");
        //如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化
        //context.getBean("startQuertz");
        System.out.print("Test end..");
       

    }

}

我们需要把log4j的配置文件放入src目录下,启动main类就可以了。

3. 设置web.xml对Spring加载

<!-- 加载spring -->
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>
    /WEB-INF/classes/applicationContext*.xml
   </param-value>
</context-param>
<servlet>
   <servlet-name>context</servlet-name>
   <servlet-class>
    org.springframework.web.context.ContextLoaderServlet
   </servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

注意:1.导入quartz-all-1.5.2.jar  下载http://download.csdn.net/source/1026766
           2.导入spring.jar(我用的是spring2.0以前的版本)  下载http://download.csdn.net/source/1041819
              如果不导入的话
               org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
              org.springframework.scheduling.quartz.CronTriggerBean
              org.springframework.scheduling.quartz.SchedulerFactoryBean
              spring中的这三个类找不到,spring不能正常加载,由于第一次使用Quartz,我就是当时忽略了这一点,浪费了很多时间来调配置,其实配置一点没有错误。
            3. 你会问为什么用spring后就不用
                quartz.properties
                quartz-jobsxml   
                这两个文件了么?
                我回答:是的,它会自动找到quartz包中默认的这两个文件,如果你有特殊需要,也可以自己定义这两个文件。

附:quartz.properties
#
# Configure Main Scheduler Properties
#

org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = one

#
# Configure ThreadPool
#

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 4

#
# Configure JobStore
#

#org.quartz.jobStore.misfireThreshold = 5000

#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

# ===========================================================================
# Configure SchedulerPlugins ===============================================
# ===========================================================================
#org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingTriggerHistoryPlugin
#org.quartz.plugin.triggHistory.triggerFiredMessage = Trigger {1}.{0} fired job {6}.{5} at: {4, date, HH:mm:ss MM/dd/yyyy}
#org.quartz.plugin.triggHistory.triggerCompleteMessage = Trigger {1}.{0} completed firing job {6}.{5} at {4, date, HH:mm:ss MM/dd/yyyy} with resulting trigger instruction code: {9}

org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName =quartz_jobs.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
org.quartz.plugin.jobInitializer.failOnFileNotFound = true

org.quartz.plugin.shutdownhook.class = org.quartz.plugins.management.ShutdownHookPlugin
org.quartz.plugin.shutdownhook.cleanShutdown = true

系统会根据配置文件找到quartz_jobs.xml

     配置之后,发现总是报错:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.scheduling.quartz.SchedulerFactoryBean#0' defined in ServletContext resource [/WEB-INF/spring/applicationContext-others.xml]: Invocation of init method failed; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: Table 'lbassnew.qrtz_locks' doesn't exist [See nested exception: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'lbassnew.qrtz_locks' doesn't exist]]

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)

浏览了一翻配置文件,发现项目原先已经有相关的quartz配置代码,于是将自己配置的SchedulerFactoryBean去掉,直接将配置的调度器放入已有的SchedulerFactoryBean中,启动,无错。

其次,在配置调度时间的时候,如果配置的启动时间为:0 50-55 16 * * ?那么,即时配置的 <property name="concurrent" value="true"/> ,启动之后也需要等待到配置的时间才会启动任务。特此记录。



spring定时任务时间格式cronExpression设置

 

 

org.springframework.scheduling.quartz.CronTriggerBean允许你更精确地控制任务的运行时间,只需要设置其cronExpression属性。
一个cronExpression表达式有至少6个(也可能是7个)由空格分隔的时间元素。从左至右,这些元素的定义如下:
1.秒(0–59)
2.分钟(0–59)
3.小时(0–23)
4.月份中的日期(1–31)
5.月份(1–12或JAN–DEC)
6.星期中的日期(1–7或SUN–SAT)
7.年份(1970–2099)
0 0 10,14,16 * * ? 每天上午10点,下午2点和下午4点
0 0,15,30,45 * 1-10 * ? 每月前10天每隔15分钟
30 0 0 1 1 ? 2012 在2012年1月1日午夜过30秒时
0 0 8-5 ? * MON-FRI 每个工作日的工作时间 

各个时间可用值如下:
秒 0-59 , – * /
分 0-59 , – * /
小时 0-23 , – * /
日 1-31 , – * ? / L W C
月 1-12 or JAN-DEC , – * /
周几 1-7 or SUN-SAT , – * ? / L C #
年 (可选字段) empty, 1970-2099 , – * /

可用值详细分析如下:

“*”——字符可以用于所有字段,在“分”字段中设为”*”表示”每一分钟”的含义。

“?”——字符可以用在“日”和“周几”字段. 它用来指定 ‘不明确的值’. 这在你需要指定这两个字段中的某一个值而不是另外一个的时候会被用到。在后面的例子中可以看到其含义。

“-”——字符被用来指定一个值的范围,比如在“小时”字段中设为”10-12″表示”10点到12点”。

“,”——字符指定数个值。比如在“周几”字段中设为”MON,WED,FRI”表示”the days Monday, Wednesday, and Friday”。

“/”——字符用来指定一个值的的增加幅度. 比如在“秒”字段中设置为”0/15″表示”第0, 15, 30, 和 45秒”。而 “5/15″则表示”第5, 20, 35, 和 50″. 在’/'前加”*”字符相当于指定从0秒开始. 每个字段都有一系列可以开始或结束的数值。对于“秒”和“分”字段来说,其数值范围为0到59,对于“小时”字段来说其为0到23, 对于“日”字段来说为0到31, 而对于“月”字段来说为1到12。”/”字段仅仅只是帮助你在允许的数值范围内从开始”第n”的值。

“L”——字符可用在“日”和“周几”这两个字段。它是”last”的缩写, 但是在这两个字段中有不同的含义。例如,“日”字段中的”L”表示”一个月中的最后一天” —— 对于一月就是31号对于二月来说就是28号(非闰年)。而在“周几”字段中, 它简单的表示”7″ or “SAT”,但是如果在“周几”字段中使用时跟在某个数字之后, 它表示”该月最后一个星期&times;” —— 比如”6L”表示”该月最后一个周五”。当使用’L'选项时,指定确定的列表或者范围非常重要,否则你会被结果搞糊涂的。

“W”——可用于“日”字段。用来指定历给定日期最近的工作日(周一到周五) 。比如你将“日”字段设为”15W”,意为: “离该月15号最近的工作日”。因此如果15号为周六,触发器会在14号即周五调用。如果15号为周日, 触发器会在16号也就是周一触发。如果15号为周二,那么当天就会触发。然而如果你将“日”字段设为”1W”, 而一号又是周六, 触发器会于下周一也就是当月的3号触发,因为它不会越过当月的值的范围边界。’W'字符只能用于“日”字段的值为单独的一天而不是一系列值的时候。

“L”和“W”可以组合用于“日”字段表示为’LW’,意为”该月最后一个工作日”。

“#”—— 字符可用于“周几”字段。该字符表示“该月第几个周&times;”,比如”6#3″表示该月第三个周五( 6表示周五而”#3″该月第三个)。再比如: “2#1″ = 表示该月第一个周一而 “4#5″ = 该月第五个周三。注意如果你指定”#5″该月没有第五个“周&times;”,该月是不会触发的。

“C”—— 字符可用于“日”和“周几”字段,它是”calendar”的缩写。 它表示为基于相关的日历所计算出的值(如果有的话)。如果没有关联的日历, 那它等同于包含全部日历。“日”字段值为”5C”表示”日历中的第一天或者5号以后”,“周几”字段值为”1C”则表示”日历中的第一天或者周日以后”。

对于“月份”字段和“周几”字段来说合法的字符都不是大小写敏感的。

一些例子:
“0 0 12 * * ?” 每天中午十二点触发
“0 15 10 ? * *” 每天早上10:15触发
“0 15 10 * * ?” 每天早上10:15触发
“0 15 10 * * ? *” 每天早上10:15触发
“0 15 10 * * ? 2005″ 2005年的每天早上10:15触发
“0 * 14 * * ?” 每天从下午2点开始到2点59分每分钟一次触发
“0 0/5 14 * * ?” 每天从下午2点开始到2:55分结束每5分钟一次触发
“0 0/5 14,18 * * ?” 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
“0 0-5 14 * * ?” 每天14:00至14:05每分钟一次触发
“0 10,44 14 ? 3 WED” 三月的每周三的14:10和14:44触发
“0 15 10 ? * MON-FRI” 每个周一、周二、周三、周四、周五的10:15触发
“0 15 10 15 * ?” 每月15号的10:15触发
“0 15 10 L * ?” 每月的最后一天的10:15触发
“0 15 10 ? * 6L” 每月最后一个周五的10:15

转载于:https://my.oschina.net/jibaole/blog/287230

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值