1. 程式人生 > >Java Web 定時任務

Java Web 定時任務

使用的java web框架是spring+springmvc,當web服務啟動以後,會有一個定時的任務去完成某一些特定的功能。在定時任務中支援註解其他的service等。

1、首先,在applicationContext-mvc.xml(xml配置檔案的名稱可能不一樣)檔案中,需要有這樣一段程式碼

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <context:component-scan base-package="com.xxx.logic"/>

    <bean class="com.xxx.SyncPro"></bean>

    <bean id="sessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.xxx.model"/>
        <property name="configLocation" value="/WEB-INF/mybatis-config.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
        <property name="basePackage" value="com.xxx.mapper"/>
    </bean>

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
        <qualifier value="txm"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="freemarkerViewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="order" value="1"/>
        <property name="suffix" value=".html"/>
        <property name="contentType" value="text/html;charset=utf-8"/>
        <property name="exposeRequestAttributes" value="true"/>
        <property name="exposeSessionAttributes" value="true"/>
        <property name="exposeSpringMacroHelpers" value="true"/>
        <property name="requestContextAttribute" value="rc"/>
        <property name="redirectHttp10Compatible" value="false"/>
        <property name="viewClass">
            <value>com.xxx.FreeMarkerView
            </value>
        </property>
    </bean>

    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">5</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="locale">UTF-8</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="number_format">0.####</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="whitespace_stripping">true</prop>
                <prop key="tag_syntax">auto_detect</prop>
                <prop key="url_escaping_charset">UTF-8</prop>
            </props>
        </property>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="4096"/>
    </bean>

    <mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.xxx.AuthInterceptor">
        </bean>
    </mvc:interceptor>
</mvc:interceptors>

</beans>

可以找到這樣一段程式碼 :

<bean class="com.xxx.SyncPro"></bean>

2、其次,核心程式碼這樣寫

package com.xxx.main;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by niyl 2018/7/26
 */
public class SyncPro implements InitializingBean {

    private static final Logger logger = Logger.getLogger(SyncPro.class);

    @Override
    public void afterPropertiesSet() throws Exception {
        new GetWebSiteTH().start();
    }

    class GetWebSiteTH extends Thread {
        public void run() {
            while (true) {
                try {
                    logger.info("SYS|SyncPro|定時訪問網站xxx.com|"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                    HttpClient client = new HttpClient();
                    Thread.sleep(6 * 60 * 60 * 1000L);
                } catch (Exception e) {
                    logger.error("SYS|SyncPro|定時訪問網站xxx.com出錯|", e);
                }
            }
        }
    }

}

即可完成javaweb 的定時任務。其實可以在java程式碼中加入註解 

@Autowired

private UsrService usrService;

我在這裡並沒有寫。

定時效果如下: