JAVA任务调度实现方法一

背景:目前因工作需要,要实现WEB项目设计动态加载XML文件的功能。这些XML文件的数据是动态从数据库中获取到的,其中数据库中数据每一小时更新一次。因此需要每一小时动态生成XML文件。这就要用到JAVA中得任务调度功能。

总的来说,分为两部分:1.项目启动时通过servlet调度任务;2.通过JAVA QUARTS 每一小时进行一次任务调度。

 

项目架构:SSH(struts2+spring+hibernate)

 

言归正传,进入正题,开始讨论这两种方法的实现.

 

一 servlet 任务调度

 

1. web.xml 中servlet的配置

 

<servlet>
	<servlet-name>CreateXmlForCharts</servlet-name>
	<servlet-class>cn.gov.cma.servlet.CreateXmlForCharts</servlet-class>
		 
	<load-on-startup>3</load-on-startup>
		
</servlet>

<servlet-mapping>
	<servlet-name>CreateXmlForCharts</servlet-name>
	<url-pattern>/XmlTools/CreateXmlForCharts</url-pattern>
</servlet-mapping>

 2. servlet 的任务调度 方法

protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String xpwd = request.getParameter("xpwd");
		if (xpwd == null || !xpwd.equals("administrator"))
			return;

		System.out
				.println("-------------CreateXmlForCharts------anytime ---------"
						+ new Date());
		// 获取SPRING中的<bean>节点的globalQueue队列对象。
		WebApplicationContext webapplicationcontext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		ICreateXmlForChartsService createxmlforchartsservice = (CreateXmlForChartsServiceImpl) webapplicationcontext
				.getBean("createxmlforchartsservice");
		long starta = System.currentTimeMillis();
		List<Integer> list = createxmlforchartsservice.findAllStationID();// stationid
																			// 的list
																			// 之后按此list进行生成xml的动作.
		long startb = System.currentTimeMillis();
		System.out.println(startb - starta
				+ "========findAllStationID======time");
		System.out.println(list.size());
		String[] hours = DateUtils.getTimeString(24);// 指定时间段字符串数组.
		// for(String h:hours) System.out.println(h);

		System.out.println("_+_+_+_+_+_+_+_");
		String[] sbtime = DateUtils.getTimeBeginAndEndString(24);
		// for(String h:sbtime) System.out.println(h);

		long startc = System.currentTimeMillis();
		Map<String, EleAwstPublicvo> map = createxmlforchartsservice
				.findAllEleAwstPublic(sbtime[1], sbtime[0]);// 存放着指定时间段内,所有的stationid对应的实况信息.
		long startd = System.currentTimeMillis();
		System.out.println(startd - startc
				+ "========findAllEleAwstPublic======time");
		System.out.println(map.size());
		int listsize = list.size();
		Integer stationid;
		List<EleAwstPublicvo> listEleAwstPublicvo;
		PrintWriter out;
		//String filepath = "/usr/product/apache-tomcat-6.0.32/webapps/productdb_flex/demo/";
		String filepath = "D:/productdb/tomcat 6/webapps/productdb_flex/demo/";
		File filefolder = new File(filepath);
		if (!filefolder.exists())
			filefolder.mkdirs();
		for (int i = 0; i < listsize; i++) {
			stationid = list.get(i);
			listEleAwstPublicvo = CreateXml.getEleAwstPublicvolistByStationID(
					stationid, map, hours);
			if (stationid == 45011) {
				for (EleAwstPublicvo o : listEleAwstPublicvo) {
					System.out.println(o.getV01000() + "|" + o.getcBjtime()
							+ "|" + o.getV12001() + "|" + o.getV11043() + "|"
							+ o.getV11041() + "|" + o.getV13003() + "|"
							+ o.getV13019());
				}
			}

			out = new PrintWriter(

			filepath + stationid + "temperature.xml", "gb2312");
			CreateXml.createTemperatureXml(stationid, listEleAwstPublicvo, out);
			out = new PrintWriter(

			filepath + stationid + "humidity.xml", "gb2312");
			CreateXml.createHumidityXml(stationid, listEleAwstPublicvo, out);
			out = new PrintWriter(

			// //"out\\"+ 需要就自己加上文件夹名称
					filepath + stationid + "wind.xml", "gb2312");
			CreateXml.createWindXml(stationid, listEleAwstPublicvo, out);
			out = new PrintWriter(

			filepath + stationid + "precipitation.xml", "gb2312");
			CreateXml.createPrecipitationXml(stationid, listEleAwstPublicvo,
					out);

		}
		long starte = System.currentTimeMillis();
		System.out.println(starte - startd
				+ "========compare and write xml======time");

	}

 

关键点:

WebApplicationContext webapplicationcontext = WebApplicationContextUtils
    .getRequiredWebApplicationContext(this.getServletContext());
  ICreateXmlForChartsService createxmlforchartsservice = (CreateXmlForChartsServiceImpl) webapplicationcontext
    .getBean("createxmlforchartsservice");

首先:通过SPRING提供的WebApplicationContextUtils 类方法得到WebApplicationContext的对象;

然后:通过WebApplicationContext对象得到service bean 对象;

之后就可以调用service方法,即业务方法。

很简单,是不是,(:-:)

 

二 QUARTS任务调度实现

1. 首先介绍一下QUARTS, Quartz是OpenSymphony提供的任务调度库类。借助一SPRING对QUARTS的很好的支持,可以很方便的使用这套任务调度库类。

以下是SPRING中QUARTS得配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">


        <!-- 要调用的工作类 -->
        <bean id="quartzJob" class="cn.gov.cma.quartzs.CreateXmlForCharts">
        <property name="createxmlforchartsservice" ref="createxmlforchartsservice"></property>
        </bean>
        <!-- 定义调用对象和调用对象的方法 -->
        <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <!-- 调用的类 -->
            <property name="targetObject">
                <ref bean="quartzJob"/>
            </property>
            <!-- 调用类中的方法 -->
            <property name="targetMethod">
                <value>createXml</value>
            </property>
        </bean>
        <!-- 定义触发时间 -->
        <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
            <property name="jobDetail">
                <ref bean="jobtask"/>
            </property>
            <!-- cron表达式 -->
            <property name="cronExpression">
                <!-- 每隔2秒执行一次-->
                <value>0 45 * * * ?</value>
            </property>
        </bean>
        <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
        <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
                    <ref bean="doTime"/>
                </list>
            </property>
        </bean>
<!-- 接收数据的servlet -->

</beans>

 

总的意思每个小时的第45分钟,系统会自动调用生成XML文件的方法。

2. 此方法以方面servlet的任务调度方法类似。

 

public void createXml() {

		System.out
				.println("-------------CreateXmlForCharts------quartzs ---------"
						+ new Date());

		long starta = System.currentTimeMillis();
		List<Integer> list = createxmlforchartsservice.findAllStationID();// stationid
																			// 的list
																			// 之后按此list进行生成xml的动作.
		long startb = System.currentTimeMillis();
		System.out.println(startb - starta
				+ "========findAllStationID======time");
		System.out.println(list.size());
		String[] hours = DateUtils.getTimeString(24);// 指定时间段字符串数组.
		// for(String h:hours) System.out.println(h);

		System.out.println("_+_+_+_+_+_+_+_");
		String[] sbtime = DateUtils.getTimeBeginAndEndString(24);
		// for(String h:sbtime) System.out.println(h);

		long startc = System.currentTimeMillis();
		Map<String, EleAwstPublicvo> map = createxmlforchartsservice
				.findAllEleAwstPublic(sbtime[1], sbtime[0]);// 存放着指定时间段内,所有的stationid对应的实况信息.
		long startd = System.currentTimeMillis();
		System.out.println(startd - startc
				+ "========findAllEleAwstPublic======time");
		System.out.println(map.size());
		int listsize = list.size();
		Integer stationid;
		List<EleAwstPublicvo> listEleAwstPublicvo;
		PrintWriter out;
		//String filepath = "/usr/product/apache-tomcat-6.0.32/webapps/productdb_flex/demo/";
		String filepath = "D:/productdb/tomcat 6/webapps/productdb_flex/demo/";
		File filefolder = new File(filepath);
		if (!filefolder.exists())
			filefolder.mkdirs();
		try {
			for (int i = 0; i < listsize; i++) {
				stationid = list.get(i);
				listEleAwstPublicvo = CreateXml
						.getEleAwstPublicvolistByStationID(stationid, map,
								hours);
				/*
				 * if(i==500){ for(EleAwstPublicvo o:listEleAwstPublicvo ) {
				 * System
				 * .out.println(o.getV01000()+"|"+o.getcBjtime()+"|"+o.getV12001
				 * (
				 * )+"|"+o.getV11043()+"|"+o.getV11041()+"|"+o.getV13003()+"|"+o
				 * .getV13019()); } }
				 */

				out = new PrintWriter(

				filepath + stationid + "temperature.xml", "gb2312");
				CreateXml.createTemperatureXml(stationid, listEleAwstPublicvo,
						out);
				out = new PrintWriter(

				filepath + stationid + "humidity.xml", "gb2312");
				CreateXml
						.createHumidityXml(stationid, listEleAwstPublicvo, out);
				out = new PrintWriter(

				// //"out\\"+ 需要就自己加上文件夹名称
						filepath + stationid + "wind.xml", "gb2312");
				CreateXml.createWindXml(stationid, listEleAwstPublicvo, out);
				out = new PrintWriter(

				filepath + stationid + "precipitation.xml", "gb2312");
				CreateXml.createPrecipitationXml(stationid,
						listEleAwstPublicvo, out);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		long starte = System.currentTimeMillis();
		System.out.println(starte - startd
				+ "========compare and write xml======time");
	}

 Over....

后续要补充一下java.util.Timer任务调度实现。

 

你可能感兴趣的:(java)