第一种方式
package cn.mldn.util; import java.text.SimpleDateFormat; public class MyTask2 { public void runJob() { System.out.println("*** [当前日期时间]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date())); } }
applicationContext
<bean id="myTask" class="cn.mldn.util.MyTask2" />
<task:scheduled-tasks>
<!-- <task:scheduled ref="myTask" method="runJob" fixed-rate="2000"/> -->
<task:scheduled ref="myTask" method="runJob" cron="0 * * * * ?"/>
</task:scheduled-tasks>
第二种方式
package cn.mldn.util; import java.text.SimpleDateFormat; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask2 { //@Scheduled(fixedRate=2000) //间隔触发 @Scheduled(cron="0 * * * * ?") public void runJob() { System.out.println("*** [当前日期时间]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date())); } }
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd"> <!-- 表示现在启用Annotation配置,配置的只能够是任务 --> <task:annotation-driven/> <task:scheduler id="myScheduler" pool-size="20"/> <!-- 表示多个任务彼此之间的延迟不会影响 --> <context:annotation-config /> <context:component-scan base-package="cn.mldn" /> </beans>