【spring】task 任务调度(定时任务)

1.定时任务的几种实现可以看这里:http://gong1208.iteye.com/blog/1773177

2.需要导入spring的jar包,可以参看之前的【spring】相关文章

3.这里使用的是基于注解的方式完成定时任务,在spring的配置文件中配置如下 applicationContext.xml:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">
  <context:component-scan base-scan="com.raipeng.work.spring.task"/>
  <task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/>
  <task:executor id="executor" pool-size="5"/>
  <task:scheduler id="scheduler" pool-size="10"/>
</beans>

4.需要定时的 HelloWorldTask.java

package com.raipeng.work.spring.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Created by 111 on 2015/11/23.
 */
@Component
public class HelloWorldTask {

    @Scheduled(cron = "0 * 16 * * ?")  //每天从下午四点到四点59分每分钟执行一次
    public void sayHello(){
        System.out.println("hello world!");
    }
}

 

5.控制台打印结果

INFO: Root WebApplicationContext: initialization completed in 930 ms
[2015-11-23 04:46:12,680] Artifact work-test:war exploded: Artifact is deployed successfully
[2015-11-23 04:46:12,680] Artifact work-test:war exploded: Deploy took 2,397 milliseconds
十一月 23, 2015 4:46:19 下午 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory D:\Program Files\apache-tomcat-7.0.59-windows-x64\apache-tomcat-7.0.59\webapps\manager
十一月 23, 2015 4:46:19 下午 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory D:\Program Files\apache-tomcat-7.0.59-windows-x64\apache-tomcat-7.0.59\webapps\manager has finished in 83 ms
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!

6.cronExpression(时间表达式)具体使用方法可以看这里:cronExpressiion表达式

7.以上只是一个简单的使用,定时任务可以用于日志分析,选择定时在午夜完成。

 

posted @ 2015-11-23 17:14  沧海一粟,志取一瓢  Views(3919)  Comments(0Edit  收藏  举报