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.以上只是一個簡單的使用,定時任務可以用於日志分析,選擇定時在午夜完成。