Spring设置定时器配置

我是研究僧i 提交于 2020-03-04 10:10:53

corn表达式生成:http://www.pppet.net/

 

1.注解方式

添加命名空间

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

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-4.0.xsd

task任务扫描注解

<task:annotation-driven/>

spring扫描位置

<context:annotation-config/>

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

定时任务

@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次

public void myTest(){

System.out.println("进入测试");

注意:定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true)

 

2.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd    
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">        
    
    <!-- 定时任务 -->
    <bean id="venueLockerRecordJob" class="com.rdkl.qmjs.job.VenueLockerRecordJob"/>    
    <bean id="venueLockerRecordJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="venueLockerRecordJob" />
        <property name="targetMethod" value="updateStatus" /> 
        <!-- false:不允许并发执行 -->
        <property name="concurrent" value="false" /> 
    </bean>    
    <bean id="venueSettlementJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="description" value="更新储物柜租用状态" />
        <property name="jobDetail" ref="venueLockerRecordJobDetail" />
        <!-- 凌晨2点执行  0 0 2 * * ? -->
        <property name="cronExpression" value="0 0 12 * * ?" />
    </bean>
    <!-- 定时任务配置 结束 -->
    
    <!-- schedulerFactory -->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>                                                  
                <ref bean="venueSettlementJobTrigger" /> 
            </list>
        </property>
    </bean>
</beans>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!