参考:http://blog.csdn.net/u011116672/article/details/52517247
1 spring 配置
spring task:scheduler
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean id="jobdemo" class="com.xxx.job.AbstractSingleJob" />
<task:scheduler id="scheduler" pool-size="6" />
<task:scheduled-tasks scheduler="scheduler">
<!-- 每10s 执行一次任务 秒 分 时 天 月 年 -->
<task:scheduled ref="jobdemo" method="execute" cron="0/10 * * * * ?" />
</task:scheduled-tasks>
</beans>
2 java调用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AbstractSingleJob {
private static boolean RUNNING = false;
protected String name = this.getClass( ).getSimpleName( );
protected Logger logger = LoggerFactory.getLogger( AbstractSingleJob.class );
final public void execute( ) {
logger.info( "{} START...", name );
synchronized( AbstractSingleJob.class ) {
if( RUNNING ) {
return;
}
RUNNING = true;
}
try {
doExcute( );
} catch( Exception e ) {
logger.error( "{} occur error ", name, e );
} finally {
logger.info( "{} END...", name );
RUNNING = false;
}
}
/**
* 执行体
*/
protected void doExcute( ) {
}
public void setName( String name ) {
this.name = name;
}
public String getName( ) {
if( this.name == null ) {
return this.getClass( ).getSimpleName( );
}
return name;
}
}
3 cron说明
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
按顺序依次为
秒(0~59)
分钟(0~59)
小时(0~23)
天(月)(0~31,但是你需要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7.年份(1970-2099)
其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置?.
0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时