如下:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns="http://www.springframework.org/schema/beans" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <!-- spring的Scheduler 定时器 需要启动项目后才能运行--> <task:scheduler id="myScheduler" pool-size="10"/> <task:annotation-driven scheduler="myScheduler" mode="proxy" /> </beans> @Component public class ScheduleTask { @Scheduled(cron="0 32 15 * * ?") //每天的15点32执行 public void testTask() { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(" ************************************************ "); System.out.println(" 定时任务开始 "+sdf.format(new Date())); System.out.println(" ************************************************ "); for(int i = 0; i <= 5; i++) { System.out.println(i); } System.out.println(" ************************************************ "); System.out.println(" 定时任务结束 "+sdf.format(new Date())); System.out.println(" ************************************************ "); } }下面列举几个例子供大家来验证:
0 0 3 * * ? 每天3点执行 0 5 3 * * ? 每天3点5分执行 0 5 3 ? * * 每天3点5分执行,与上面作用相同 0 5/10 3 * * ? 每天3点的 5分,15分,25分,35分,45分,55分这几个时间点执行 0 10 3 ? * 1 每周星期天,3点10分 执行,注:1表示星期天 0 10 3 ? * 1#3 每个月的第三个星期,星期天 执行,#号只能出现在星期的位置 15-30/5 * * * * ? 每分钟的15秒到30秒之间开始触发,每隔5秒触发一次 0 0/3 * * * ? 每小时的第0分0秒开始,每三分钟触发一次 0 15 10 ? * MON-FRI 星期一到星期五的10点15分0秒触发任务 0 15 10 L * ? 每个月最后一天的10点15分0秒触发任务 0 15 10 LW * ? 每个月最后一个工作日的10点15分0秒触发任务 0 15 10 ? * 5L 每个月最后一个星期四的10点15分0秒触发任务 0 15 10 ? * 5#3 每个月第三周的星期四的10点15分0秒触发任务