一:注解方式
<?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:task="http://www.springframework.org/schema/task"// 在xml里加入task的命名空间
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task //
http://www.springframework.org/schema/task/spring-task-3.1.xsd //
">
<!-- 启用注解驱动的定时任务 -->
<task:annotation-driven scheduler="myScheduler"/>
<!-- 推荐配置线程池,若不配置多任务下会有问题。 -->
<task:scheduler id="myScheduler" pool-size="5"/>
实例:
@Scheduled注解为定时任务,cron表达式里写执行的时机
@Component
public class SendSMS {
MSS mss = new MSS();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Scheduled(cron = "0 * * * * ? ")
public void deleteSms() {
deleteVerificationBeOverdue();
}
二:xml配置文件
(一)spring-jobs.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 定时任务集合类 -->
<bean id="statsTask" class="cn.com.infcn.stats.task.StatsTask"></bean>
<!-- 每天两点钟 执行一次 -->
<bean id="statsJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="statsTask"></property>
<property name="targetMethod" value="runTask"></property>
</bean>
<bean id="statsTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="statsJobDetail" />
</property>
<property name="cronExpression">
<value>0 0 1 * * ?</value>
</property>
</bean>
@Component
public class StatsTask {
private static final Logger logger = Logger.getLogger(StatsTask.class);
/**
* 预处理定时器
*/
public void runTask(){
logger.info("预处理任务已启动"+Tools.timeToString(new Date()));
try {
StatsUtil.sendPost(StatsUtil.getWebPath() + "/statsData", "");
} catch (Exception e) {
logger.error(ExceptionUtil.getExceptionMessage(e));
}
}