Java的几种定时任务

来源:互联网 发布:程序员爱逛的网站 编辑:程序博客网 时间:2024/06/06 03:16

1、XML文件配置的job

    web.xml

    <servlet>
        <servlet-name>QuartzInitializer</servlet-name>
        <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
        <init-param>
            <param-name>shutdown-on-unload</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>config-file</param-name>
            <param-value>quartz.properties</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>


quartz.properties

#============================================================================
# Configure Main Scheduler Properties  
#============================================================================
org.quartz.scheduler.instanceName = org.quartz.scheduler.instanceId = AUTO
#============================================================================
# Configure ThreadPool  
#============================================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 3
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure Plugins
#============================================================================
#org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin
#org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.class = com.coship.dhm.portalMS.common.util.DHMJobInitializer
#org.quartz.plugin.jobInitializer.fileName = quartz.xml
#\u5fc5\u987b\u6839\u636e\u5b9e\u9645\u60c5\u51b5\u914d\u7f6e\u6210quartz_nanjing-classify.xml\uff08\u5357\u4eac\u5206\u7ea7\uff09\u6216\u8005quartz_tianwei.xml \u6216 quartz_nanjing-no-classify.xml\uff08\u4e0d\u5206\u7ea7\uff09-->
org.quartz.plugin.jobInitializer.fileNames = quartz_tianwei.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.scanInterval = 10

quartz_tianwei.xml

<?xml version="1.0" encoding="UTF-8"?>
<quartz>
    <job>
        <job-detail>
            <name>AutoSentPublishTaskJob</name>
            <group>AutoSentPublishTaskJobGroup</group>
            <description>定时发布门户任务(Release scheduled portal task)</description>
            <job-class>com.coship.dhm.portalMS.publishMs.task.AutoSentPublishTask</job-class>
        </job-detail>
        <trigger>
            <cron>
                <name>AutoSentPublishTaskJobCron</name>
                <group>AutoSentPublishTaskJobGroup</group>
                <job-name>AutoSentPublishTaskJob</job-name>
                <job-group>AutoSentPublishTaskJobGroup</job-group>
                <cron-expression>0 * * * * ?</cron-expression>
            </cron>
        </trigger>
    </job>


</quartz>



2、spring框架

  <!-- 发送未成功的同步消息任务 -->
  <bean id="SynFailedMessageTask" class="com.coship.dhm.core.bss.service.synchronize.job.SynFailedMessageTask">
  </bean>
  <bean id="SynFailedMessageJob"
    class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject">
      <ref bean="SynFailedMessageTask" />
    </property>
    <property name="targetMethod">
      <value>doRun</value>
    </property>
  </bean>
  <bean id="SynFailedMessageTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail">
      <ref bean="SynFailedMessageJob"></ref>
    </property>
    <property name="cronExpression">
      <value>10 0/5 * * * ?</value><!--每隔5分钟 -->
    </property>
  </bean>


appContextServiceSynchronize.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
 <!-- 发送未成功的同步消息任务 -->
  <bean id="SynFailedMessageTask" class="com.coship.dhm.core.bss.service.synchronize.job.SynFailedMessageTask">
  </bean>
  <bean id="SynFailedMessageJob"
    class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject">
      <ref bean="SynFailedMessageTask" />
    </property>
    <property name="targetMethod">
      <value>doRun</value>
    </property>
  </bean>
  <bean id="SynFailedMessageTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail">
      <ref bean="SynFailedMessageJob"></ref>
    </property>
    <property name="cronExpression">
      <value>10 0/5 * * * ?</value><!--每隔5分钟 -->
    </property>
  </bean>
  .......
</beans>  

appContextService.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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
    default-lazy-init="true">

    <!-- ========================= RESOURCE DEFINITIONS ========================= -->
    
    <import resource="classpath:conf/appContextDao.xml" />
    
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource">
          <ref bean="dataSource"/>
        </property>
    </bean>
    
    <tx:advice transaction-manager="transactionManager" id="txAdvice" >
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>

   <!-- 管理事务操作 -->
    <aop:config>
        <aop:pointcut id="myPoint"
            expression="execution(* com.coship.dhm.nspAdapter.base.AbstractService.execute(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPoint" />
    </aop:config>
 
    <bean id="baseTransactionProxy" abstract="true"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager">
            <ref local="transactionManager" />
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="search*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="count*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
                <prop key="add*">PROPAGATION_REQUIRED</prop>
                <prop key="create*">PROPAGATION_REQUIRED</prop>
                <prop key="insert*">PROPAGATION_REQUIRED</prop>
                <prop key="update*">PROPAGATION_REQUIRED</prop>
                <prop key="modify*">PROPAGATION_REQUIRED</prop>
                <prop key="delete*">PROPAGATION_REQUIRED</prop>
                <prop key="shift*">PROPAGATION_REQUIRED</prop>
                <prop key="del*">PROPAGATION_REQUIRED</prop>
                <prop key="remove*">PROPAGATION_REQUIRED</prop>
                <prop key="upload*">PROPAGATION_REQUIRED</prop>
                <prop key="purchase*">PROPAGATION_REQUIRED</prop>
                <prop key="cancel*">PROPAGATION_REQUIRED</prop>
                <prop key="do*">PROPAGATION_REQUIRED</prop>
                <prop key="*Delete">PROPAGATION_REQUIRED</prop>
                <prop key="active*">PROPAGATION_REQUIRED</prop>
                <prop key="preActive*">PROPAGATION_REQUIRED</prop>
                <prop key="sync*">PROPAGATION_REQUIRED</prop>
                <prop key="sendMessage*">PROPAGATION_REQUIRED</prop>
                <prop key="doExcute">PROPAGATION_REQUIRED</prop>
                <prop key="execute">PROPAGATION_REQUIRED</prop>
                <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
            </props>
        </property>
    </bean>
 
    <import resource="appContextServiceSynchronize.xml" />
    
    <!--<import resource="appContextServiceCatalog.xml" />
    <import resource="appContextServiceLog.xml" />
    <import resource="appContextServicePolicy.xml" />
    <import resource="appContextServicePoster.xml" />
    <import resource="appContextServiceProductAndGoods.xml" />
    <import resource="appContextServiceResourceSpec.xml" />
    <import resource="appContextServiceSpec.xml" />
     <import resource="appContextServiceSystem.xml" />
    
    <import resource="appContextServiceProvider.xml" />
    <import resource="appContextServiceCustomer.xml" />
    <import resource="appContextServiceGroup.xml" />

     --><!--
     <import resource="appContextServiceBms.xml" />  
     -->
     <!-- 参数校验AOP -->
     <bean id="serviceParaCheckInterceptor"
        class="com.coship.miss.util.intercaptor.ServiceParaCheckInterceptor">
    </bean>
    <bean id="RegexAdvisor"
        class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <property name="advice">
            <ref local="serviceParaCheckInterceptor" />
        </property>
        <property name="patterns">
            <list>
                <value>com.coship.dhm.nspAdapter.*\.execute</value>
            </list>
        </property>
    </bean>
        <!--
        <bean id="paraCheckAop" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
                <property name="beanNames">
                        <list>
                                <value>SyncGoodsServiceImpl</value>
                                <value>SyncGoodsStatusServiceImpl</value>
                                <value>SyncAddCloumnImageServiceImpl</value>
                                <value>SyncDelCloumnImageServiceImpl</value>
                                <value>SyncColumnRecommendServiceImpl</value>
                                <value>SyncProgramServiceImpl</value>
                        </list>
                </property>
                <property name="interceptorNames">
                        <list>
                                <value>serviceParaCheckInterceptor</value>
                        </list>
                </property>
        </bean>
    
     -->

</beans>



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>nspAdapter</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring/appContextService.xml,
            classpath:spring/applicationContext-operation.xml
        </param-value>
    </context-param>
    <!-- config system context values -->
    <context-param>
        <param-name>org.mule.config</param-name>
        <param-value>/WEB-INF/mule-transformer-config.xml,/WEB-INF/mule-server-config.xml</param-value>
    </context-param>
    <context-param>
        <param-name>dhm-system-name</param-name>
        <param-value>nspAdapter</param-value>
    </context-param>
    <context-param>
        <param-name>system.config-path-name</param-name>
        <param-value>conf</param-value>
    </context-param>
 
  <context-param>
        <param-name>checkConfigFilePath</param-name>
        <param-value>conf/para_check_config.xml</param-value>
    </context-param>
    
    <context-param>
        <param-name>log.config-file</param-name>
        <param-value>log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>log.config-file-refresh-interval</param-name>
        <param-value>6000</param-value>
    </context-param>

    <context-param>
        <param-name>system.log-path-name</param-name>
        <param-value>log</param-value>
    </context-param>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value> app.root </param-value>
    </context-param>
 
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
    <listener>
        <listener-class>
            com.coship.dhm.common.uif.system.StartupListener
        </listener-class>
    </listener>
    <!--    
    <listener>
        <listener-class>
            com.coship.dhm.common.init.InitSystemListener
        </listener-class>
    </listener>
    -->
    
    <listener>
        <listener-class>
            com.coship.dhm.nspAdapter.common.NSPInitUifListener
        </listener-class>
    </listener>
    
    <listener>
        <listener-class>
            com.coship.dhm.nspAdapter.common.NSPInitSerListener
        </listener-class>
    </listener>
    
    <!--
    <listener>
        <listener-class>
            com.coship.dhm.common.uif.system.ACFStartupListener
        </listener-class>
    </listener>
    
    <listener>
        <listener-class>
            com.coship.dhm.aaa.daf.DAFStartListener
        </listener-class>
    </listener>
    -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <filter>
        <filter-name>ipAuthFilter</filter-name>
        <filter-class>com.coship.dhm.common.uif.system.IpAuthFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ipAuthFilter</filter-name>
        <url-pattern>/services/*</url-pattern>
    </filter-mapping>
    
    <!--<servlet>
        <servlet-name>MonitorServlet</servlet-name>
        <servlet-class>
            com.coship.aaa.monitor.servlet.MonitorServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    -->
    
    <listener>
    <listener-class>com.coship.backupmode.listener.JBackupListener</listener-class>
  </listener>
 
    <listener>
        <listener-class>
            com.coship.dhm.nspAdapter.common.util.AdapterDBInitListener
        </listener-class>
  </listener>
    
    <servlet>
        <servlet-name>muleServlet</servlet-name>
        <servlet-class>
            org.mule.transport.servlet.MuleReceiverServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>muleServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>



3、Timer
public class SystemXmlFileTask extends TimerTask
    public void run()
    {
        
        try
        {
            init();
            
        }
        catch (Exception e)
        {
            logger.error("SystemXmlFileTask Exception" + e.getMessage());
        }
    }

//1.初始化系统配置文件刷新时间
    int systemRefreshInterval = 60000;
    try
    {
        systemRefreshInterval = Integer.parseInt(ctx.getInitParameter(SYSTEM_REFRESH_INTERVAL));
    }
        
 SystemXmlFileTask systemXmlFileTask = new SystemXmlFileTask(
                    configPath + FS + SYSTEMCONFIG_FILE_NAME);
            systemXmlFileTask.init();
            Timer timer = new Timer();
            timer.schedule(systemXmlFileTask,
                    systemRefreshInterval,
                    systemRefreshInterval);

0 0
原创粉丝点击