Spring Quartz定时器入门

第一步:导入必须要的包
spring核心包
spring-contxet-support-3.2.0.M2.jar
quartz-all-1.6.3.jar
commons-collections-3.1.jar
(如果有报错,可能还要导入slf4j-api-1.7.25.jar和slf4j-log4j-1.7.25.jar这两个包)
第二步:创建定时器的pojo类

//定时器
public class OrderTimeTask {
    private OrderService orderService;

    public OrderService getOrderService() {
        return orderService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }


    public void timeTask(){

        String payment = "未支付";
        String userId = UserAction.userId;

         List<Order> orders = orderService.getMyOrderByPayment(userId,payment);

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long ns = 1000;

        for(Order order:orders){
            long orderTime = order.getOrderTime().getTime();
            long nowTime = new Date().getTime();
            long diff = nowTime - orderTime;
            long sec = diff / ns;
            if(sec >5*60*60){
                orderService.deleteOrderByOrderId(order.getOrderId());
            }
        }
    }

}        

第三步:配置想spring的applicationContext.xml文件

 <!--创建定时任务的实体类bean-->
    <bean name="orderTimeTask" class="com.wxj.timer.OrderTimeTask">
        <property name="orderService" ref="orderService"></property>
    </bean>

    <!--配置方法(任务)-->
    <bean name="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 目标对象 -->
        <property name="targetObject" ref="orderTimeTask"></property>
        <!-- 是否同时发生 -->
        <property name="concurrent" value="false"></property>
        <!-- 目标方法 -->
        <property name="targetMethod" value="timeTask"></property>
    </bean>

    <!--配置执行任务的时间间隔-->
    <bean name="cronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail"></property>
        <!-- 这里的间隔时间的配置,如果不会配置,可以参考时间配置规则 -->
        <property name="cronExpression" value="0 0/1 * * * ?"></property>

    </bean>

    <!--开启定时任务-->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTriggerBean"/>
            </list>
        </property>
    </bean>

ok定时器完成了!!!

阅读更多
文章标签: spring quartz
个人分类: ssh框架搭建
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭