使用SpringMVC自带的@Scheduled完成定时任务

首先在xml配置文件头中添加以下几行:
 
 
在xml中添加配置:<task:annotation-driven />
 
配置自动扫描:
<context:component-scan base-package="com.practice.*" />
 
在要进行定时任务的类前加上 @Component
在定时任务的方法上加上 @Scheduled(corn = "")
corn的内容下面介绍
完成后启动项目,springMVC会自动扫描并完成定时任务。我的例子如下:
 
 1 package com.practice.prac.service.Impl;
 2  
 3 import java.text.DateFormat;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6  
 7 import javax.annotation.Resource;
 8  
 9 import org.springframework.scheduling.annotation.Scheduled;
10 import org.springframework.stereotype.Component;
11 import org.springframework.stereotype.Service;
12  
13 import com.practice.prac.dao.CreateTableByDayMapper;
14 import com.practice.prac.service.CreateTableByDayService;
15  
16 @Service("CreateTableByDayService")
17 @Component
18 public class CreateTableByDayImpl implements CreateTableByDayService {
19  
20     @Resource
21     CreateTableByDayMapper createTableByDayMapper;
22  
23     @Override
24     @Scheduled(cron = "*/5 * * * * ?")
25     public void createTable() {
26  
27         DateFormat fmt = new SimpleDateFormat("yyyyMMdd");
28                 String time = fmt.format(new Date());
29                 String sql = "create table if not exists table_name_" + time
30                         + " (name varchar(50),value varchar(50))";
31                 createTableByDayMapper.createTable(sql);
32     }
33  
34 }
CreateTableByDyImpl.java
corn的配置情况如下:
CRON表达式  含义 
"0 0 12 * * ?"   每天中午十二点触发 
"0 15 10 ? * *"   每天早上10:15触发 
"0 15 10 * * ?"   每天早上10:15触发 
"0 15 10 * * ? *"  每天早上10:15触发 
"0 15 10 * * ? 2005"  2005年的每天早上10:15触发 
"0 * 14 * * ?"   每天从下午2点开始到2点59分每分钟一次触发 
"0 0/5 14 * * ?"  每天从下午2点开始到2:55分结束每5分钟一次触发 
"0 0/5 14,18 * * ?"  每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 
"0 0-5 14 * * ?"   每天14:00至14:05每分钟一次触发 
"0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发 
"0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发
 
具体参见这边博客:http://biaoming.iteye.com/blog/39532
原文地址:https://www.cnblogs.com/kangyun/p/5616098.html