使用Spring的@Scheduled实现定时任务

来源:互联网 发布:php 字符串查找函数 编辑:程序博客网 时间:2024/05/16 08:32

很简单,直接贴代码。


1、spring-task.xml

<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:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd    
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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扫描注解的配置 -->
    <context:component-scan base-package="com.cmcc.admin.biz.task" />
    <!-- 任务扫描注解 -->
    <task:executor id="executor" pool-size="5" />
    <task:scheduler id="scheduler" pool-size="10" />
    <task:annotation-driven executor="executor"
        scheduler="scheduler" />

</beans>

2、Task类

@Component
public class Task {
    
    /**  
     * 定时计算。每天凌晨 01:00 执行一次  
     */
    @Scheduled(cron="0 0 1 * * *")
    public void testTask() {
        System.out.println("现在是凌晨1点,开始跑定时任务啦。。。");
    }
}

这个是我打印出来的日志,周一过来看的。



=====================over============================