我新做的这块需要用定时器来自动调用,就写下。
applicationContent.xml中加入下面这句
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" //需要加的
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task //需要加的
http://www.springframework.org/schema/task/spring-task-3.2.xsd //需要加的
">
定时器优两种方式,一种是基于xml,一种是基于注解
基于xml的(在applicationContent.xml中加入下面部分)
<task:annotation-driven /> <!-- 定时器开关-->
<bean id="taskTest" class="com.yu.test.test.Test"></bean> //class是方法所在的命名空间
<task:scheduled-tasks>
<!-- 每隔五秒执行一次 -->
<task:scheduled ref="taskTest" method="test4" cron="*/5 * * * * ?" />//这里面的method是方法名
</task:scheduled-tasks>
基于注解(在applicationContent.xml中加入下面部分)
<task:annotation-driven />
<!-- 自动扫描的包名 -->
<context:component-scan base-package="com.yu.test.test" />//package就是类所在的命名空间
------------- 分割线 ------------
在需要启动的方法上加入@Scheduled,在类上加上@Component
package com.yu.test.test;
@Component
public class Test {
@Scheduled(cron = "*/5 * * * * *")
public void test4(){
System.out.println("in test4");
}
}
至于那个crond。我简单写下,详细的可以去百度。
Crond配置完整格式为: [秒] [分] [小时] [日] [月] [周] [年]
* 表示所有值,放在分钟上,也就是每分钟都会执行。
? 表示不指定值
,表示and, 如分钟上写10,13,15 也就是每小时的10,13,15分都会执行
/ 表示递增,如分钟上写*/5,也就是启动后下一分钟开始,每五分钟执行一次
-表示区间,如分钟上写10-12,也就是10,11,12分钟是,都会执行。