步骤:
1、配置spring的配置文件 spring.xml,加入命名空间
- xmlns:task="http://www.springframework.org/schema/task"
2、在spring.xml配置文件中加入schema资源
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-3.1.xsd
3、spring.xml配置文件中加入是定时任务注解启用的标签
- <task:annotation-driven/>
完整配置如下:
- <?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"
- 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 ">
- <bean id="singer" class="com.fan.demo.TimesTasks"/>
- <task:annotation-driven />
- </beans>
- @Component
- public class EbFreightTask {
- private static final Logger logger = Logger.getLogger(EbFreightTask.class);
- @Autowired
- private EbFreightService ebFreightService;
- //@Scheduled(cron="0/30 * * * * ? ") //每30秒执行一次
- //@Scheduled(cron="0 0/6 * * * ? ") //每1分钟调用一次
- //@Scheduled(cron = "0 0 0/1 * * ?") //每隔一小时执行一次
- //@Scheduled(cron="0 0 1 * * ?") //每天凌晨一点调用
- @Scheduled(cron = "0 0 0 * * ?") //每天零点开始执行 ##更多cron表达式请自行搜索
- public void bTask() {
- logger.info(this.getClass()+"定时任务开始执行……");
- try {
- Date date = new Date(System.currentTimeMillis());
- DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- ebFreightService.ExecuteOperation(); //定时任务需要具体实现的功能
- }catch (Exception e){
- logger.error(e);
- }
- }
- }