日期:2014-05-19  浏览次数:20692 次

定时任务
我在网上看了下关于定时任务的代码。
如下:
本例依据Java自身提供的接口实现,通过监听器(Listener)和定时器(Timer)定时执行某个任务(Task)。
专业的开源工具可参考Quartz:http://www.opensymphony.com/quartz/

MyListener:
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {
??
? private Timer timer = null;

? public void contextInitialized(ServletContextEvent event) {
? timer = new Timer(true);
? //设置任务计划,启动和间隔时间
? timer.schedule(new MyTask(), 0, 86400000);
? }

? public void contextDestroyed(ServletContextEvent event) {
? timer.cancel();
? }
??
}
MyTask:
import java.util.TimerTask;

public class MyTask extends TimerTask {

? public void run() {
? // System.out.println("call at " + (new Date()));
? // TODO 此处添加具体任务代码
? }

}
web.xml配置:
<listener>
<listener-class>com.fastunit.samples.listener.MyListener</listener-class>
</listener>

我想问的是,如果我的项目是个java项目。怎么配置这个监听?
引入了spring框架

------解决方案--------------------
quartz可以有自己独立配置文件,不用spring
------解决方案--------------------
1,在项目中加如下六个jar包:
commons-collections-3.2.jar
commons-logging-1.0.4.jar
commons-pool.jar
jta-1.1.jar
quartz-1.6.0.jar
spring.jar
2,java代码
Java code

package com;

import java.util.Date;

public class YouObject
{
    public void youMethod()
    {
        System.out.println(new Date()+":每隔一分钟执行一次");
    }
}

------解决方案--------------------
4,web.xml
Java code

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <!-- acegi -->
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
</web-app>

------解决方案--------------------
首先得告诉楼主,你想要实现的效果是定时执行任务。
你在web.xml 中配置
<listener>
<listener-class>com.fastunit.samples.listener.MyListener</listener-class>
</listener>
表示你启动web 服务器的时候,会实例化对象com.fastunit.samples.listener.MyListener,并且调用
public void contextInitialized(ServletContextEvent event) {
? timer = new Timer(true);
? //设置任务计划,启动和间隔时间
? timer.schedule(new MyTask(), 0, 86400000);
? }
这个方法的代码。

如果你想实现同样的效果的话,只需要在写个一main 方法在里面,并且创建com.fastunit.samples.listener.MyListener对象,然后调用contextInitialized(null)方法即可。

------解决方案--------------------
spring定时器:http://apps.hi.baidu.com/share/detail/31761760