定时执行任务的三种方法

来源:互联网 发布:飞思卡尔编程器 编辑:程序博客网 时间:2024/06/05 10:24

1)java.util.Timer

  这个方法应该是最常用的,不过这个方法需要手工启动你的任务:

  Timer timer=new Timer();

  timer.schedule(new ListByDayTimerTask(),10000,86400000);

  这里的ListByDayTimerTask类必须extends TimerTask里面的run()方法。
    如下例:
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class UntilTimerTest {

        
    public static void main(String[] args) throws IOException
    {
        Timer timer=new Timer();
        timer.schedule(new TimerTask()
        {
            @Override
            public void run() {
                long now=System.nanoTime();
                System.out.println(new Date(now));    
                
            }            
        }, 1000,1000);
        
        while(true)
        {
            int c=System.in.read();
            if(c==’c’)
                timer.cancel();
        }
    }


timer.schedule(new MyTask(event.getServletContext()), 0, 60*60*1000);

第一个参数"new MyTask(event.getServletContext())":
是 TimerTask 类,在包:import java.util.TimerTask .使用者要继承该类,并实现 public void run() 方法,因为 TimerTask 类实现了 Runnable 接口。

第二个参数"0"的意思是:(0就表示无延迟)
当你调用该方法后,该方法必然会调用 TimerTask 类 TimerTask 类 中的 run() 方法,这个参数就是这两者之间的差值,转换成汉语的意思就是说,用户调用 schedule() 方法后,要等待这么长的时间才可以第一次执行 run() 方法。

第三个参数"60*60*1000"的意思就是:
(单位是毫秒60*60*1000为一小时)
(单位是毫秒3*60*1000为三分钟)
第一次调用之后,从第二次开始每隔多长的时间调用一次 run() 方法。

      

2)ServletContextListener

  这个方法在web容器环境比较方便,这样,在web server启动后就可以

  自动运行该任务,不需要手工操作。

  将ListByDayListener implements ServletContextListener接口,在

  contextInitialized方法中加入启动Timer的代码,在contextDestroyed

  方法中加入cancel该Timer的代码;然后在web.xml中,加入listener:

  <listener>

  <listener-class>com.qq.customer.ListByDayListener</listener-class>

  </listener>

3)org.springframework.scheduling.timer.ScheduledTimerTask

  如果你用spring,那么你不需要写Timer类了,在schedulingContext-timer

  .xml中加入下面的内容就可以了:

  <?xml version="1.0" encoding="UTF-8"?>

  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

  <beans>

  <bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">

  <property name="scheduledTimerTasks">

  <list>

  <ref local="MyTimeTask1"/>

  </list>

  </property>

  </bean>

  <bean id="MyTimeTask" class="com.qq.timer.ListByDayTimerTask"/>

  <bean id="MyTimeTask1" class="org.springframework.scheduling.timer.ScheduledTimerTask">

  <property name="timerTask">

  <ref bean="MyTimeTask"/>

  </property>

  <property name="delay">

  <value>10000</value>

  </property>

  <property name="period">

  <value>86400000</value>

  </property>

  </bean>

  </beans>

另外,客户端定时器的设置:
<script>
    function registerOnlineUser(){
        Spry.Utils.loadURL("POST", "<%=wwwroot%>/systemmgt/OnlineUserRegister.do?act=register", false);
    }
    window.setInterval("registerOnlineUser()",60*1000);   
</script>

原创粉丝点击