项目____web项目中实现:一直运行某个后台小程序+定时+多任务

如何在web项目启动后就运行某个java程序段?

把xx类写成一个servlet,然后配置到web.xml中。设置这个servlet在应用启动之后就运行。项目中web.xml配置代码如下:


	
		mapleServlet
		
			com.csValue.Servlet.mapleServlet
		
		1
	
	
		mapleServlet
		/mapleServlet.view
	


servlet启动后如何定时调用某个功能?

servlet随着项目的启动而启动,至于servlet中如何实现定时可以参考 实现定时功能 中的三种方法实现。

本项目中的mapleServlet代码如下:

package com.csValue.Servlet;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Timer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class mapleServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;

  public void init()
    throws ServletException
  {
    System.out.println("监控启动");

    Timer timer = new Timer();
    timer.schedule(new Task(), 6000L, 30000L);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doPost(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
  }
}
默认执行init方法 实例化Timer,并调用timer的schedule方法。延迟多少毫秒后。每隔多少毫秒执行一次Task。


利用Timer实现定时功能的总体步骤,用代码表示如下:

package scheduleTest;

import java.util.Timer;
import java.util.TimerTask;

public class scheduleTimerTest {
  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        // task to run goes here
        System.out.println("Hello !!!");
      }
    };
    Timer timer = new Timer();
    long delay = 5000;
    long intevalPeriod = 1 * 1000;
    // schedules the task to be run in an interval
    timer.scheduleAtFixedRate(task, delay,
                                intevalPeriod);
  } // end of main
}
实例化Timer,调用scheduleAtFixedRate方法。其中传入的task参数在之前实例化,run方法中是具体实现:输出hello

至于Timer的源码研究请参照timer研究。其中给出了关于Timer源码的具体实现,通过queue实现队列中各任务的notify。

而task是具体任务内容,代码如下:

public class Task extends TimerTask
{
  public void run()
  {
	Map changedLines=compareMapleBean(selectLocalMapleList(), selectMapleList());
    if (changedLines != null)
    {

    	  Object[] lines=changedLines.keySet().toArray();
    	  Map usageLine=new HashMap();
    	  usageLine.put("UVA 1", "");
    	  usageLine.put("UVA 2", "");
    	  usageLine.put("UVA 3", "");
    	  usageLine.put("UVA 4", "");
    	  usageLine.put("UVA 5", "");
    	  usageLine.put("UVA 6", "");
    	  usageLine.put("UVA 7", "");
    	  usageLine.put("UVA 8", "");
    	  usageLine.put("JINYI 9", "");
    	  usageLine.put("JINYI 10", "");
    	  usageLine.put("JINYI 11", "");
    	  usageLine.put("JINYI 12", "");
    	  usageLine.put("JINYI 13", "");
    	  usageLine.put("JINYI 14", "");
    	  usageLine.put("JINYI 15", "");
    	  usageLine.put("JINYI 16", "");
    	  usageLine.put("JINYI 17", "");
    	  usageLine.put("JINYI 18", "");
    	  usageLine.put("JINYI 19", "");
    	       
    	  for (Object object : lines) {
    		  if(usageLine.containsKey(object.toString())){
    			  updateMaple(object.toString(),changedLines.get(object.toString()).toString().split("::"));
    		  }
    	  }
        System.out.println("推送完成");
      }
  }
}


定时功能的具体实现?

返回来接着看servlet中的代码:

timer.schedule(new Task(), 6000L, 30000L);


实现源代码如下:

/**
     * Schedules the specified task for repeated fixed-delay execution,
     * beginning after the specified delay.  Subsequent executions take place
     * at approximately regular intervals separated by the specified period.
     *
     * 

In fixed-delay execution, each execution is scheduled relative to * the actual execution time of the previous execution. If an execution * is delayed for any reason (such as garbage collection or other * background activity), subsequent executions will be delayed as well. * In the long run, the frequency of execution will generally be slightly * lower than the reciprocal of the specified period (assuming the system * clock underlying Object.wait(long) is accurate). * *

Fixed-delay execution is appropriate for recurring activities * that require "smoothness." In other words, it is appropriate for * activities where it is more important to keep the frequency accurate * in the short run than in the long run. This includes most animation * tasks, such as blinking a cursor at regular intervals. It also includes * tasks wherein regular activity is performed in response to human * input, such as automatically repeating a character as long as a key * is held down. * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if delay is negative, or * delay + System.currentTimeMillis() is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ public void schedule(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); }


sched实现源代码如下:

 /**
     * Schedule the specified timer task for execution at the specified
     * time with the specified period, in milliseconds.  If period is
     * positive, the task is scheduled for repeated execution; if period is
     * zero, the task is scheduled for one-time execution. Time is specified
     * in Date.getTime() format.  This method checks timer state, task state,
     * and initial execution time, but not period.
     *
     * @throws IllegalArgumentException if time() is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     */
    private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");

        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }




你可能感兴趣的:(项目____web项目中实现:一直运行某个后台小程序+定时+多任务)