quartz实例以及主要事项(注解)

实现任务类:

package com.vnetoo.nec.base.quartz;

import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时发送信息
 *
 * @author lingpy
 * @since 1.0
 */
@Component
@Lazy(false)
public class SendMessageJob{
    private static long time = 0;
    
     @Scheduled(cron="0 0/2 *  * * ? ")  //两分钟一次
    public void work(){  
         time++;
        System.out.println("SendMessageJob : send message " + time + ",current :" + System.currentTimeMillis());  
    }  
}

spring.xml  配置

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.1.xsd

">

<task:annotation-driven/><!-- task任务扫描注解 -->

spring.xml可以添加注解扫描的配置

xmlns:context="http://www.springframework.org/schema/context

xsi:schemaLocation="

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd

">

<context:component-scan base-package="com.vnetoo.nec" />

主要事项:

在Spring配置和Quartz集成内容时,有两点需要注意

           1、在<Beans>中不能够设置default-lazy-init="true",否则定时任务不触发,如果不明确指明default-lazy-init的值,默认是false。可使用@Lazy(false)显示确定

           2、在<Beans>中不能够设置default-autowire="byName"的属性,否则后台会报 org.springframework.beans.factory.BeanCreationException错误,这样就不能通过Bean名称自 动注入,必须通过明确引用注入

原文地址:https://www.cnblogs.com/lingepeiyong/p/3974560.html