做到数据统计相关的问题,还有商品有关自动上架等功能,需要每天定时获取商品的浏览记录,收藏记录以及下单数量等等,需要使用定时任务来处理。想到spring自带的定时任务比较简单,就用<task:annotation-driven /> 来解决。
1.首先定义一个定时操作:
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
public class Singer {
//@Scheduled(fixedDelay=1000) //第一种方式
//fixedDelay延时多少毫秒执行一次(方法执行完毕后延迟)
//@Scheduled(fixedRate=1000)//第二种方式
//fixedRate每隔多少毫秒执行一次(不用等待方法执行完毕,每隔相应时间便执行)
@Scheduled(cron="0 * * * * *") //第三种方式
//corn传入7个参数,分别是:秒,分,时,月份的日期,月份,星期几,年(指定时间来执行:0 * * * * *表示每隔1分钟就执行一次)
/* 日期参数详解
1 Seconds (0-59)
2 Minutes (0-59)
3 Hours (0-23)
4 Day of month (1-31)
5 Month (1-12 or JAN-DEC)
6 Day of week (1-7 or SUN-SAT)
7 Year (1970-2099)
取值:可以是单个值,如6;
也可以是个范围,如9-12;
也可以是个列表,如9,11,13
也可以是任意取值,使用*
*/
public void singing(){ //定时打印时间功能(每隔一分钟)
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(date));
}
}
2.Spring配置文件:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd ">
<!—开启这个配置,spring才能识别@Scheduled注解 -->
<task:annotation-driven />
</beans>
ok,然后重新启动eclipse,在控制台就会看到定时执行的输出日期任务在执行了。