@Scheduled定时器启动两次

@Scheduled定时器启动两次

引用自:https://blog.csdn.net/ID19870510/article/details/78020774#commentBox

一、portal 项目spring-datasource.xml配置


<context:component-scan base-package="org.gfg">
   <context:include-filter type="regex" expression=".portal.*"/>
   
   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
context:component-scan>

二、portal 项目spring-dispatch.xml配置


<context:component-scan base-package="org.gfg">
   <context:include-filter type="regex" expression=".portal.*"/>
   
   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
context:component-scan>

三、说明

​ spring 会给每一个 注释有 @Service @Controller @Repository @Component 的类 注入到bean ,然后进行调用,上述两个配置, @Scheduled 的类ScheduleJobs由于使用了 @Component 注入,导致注入了两次,所以定时器启动两次。当前将ScheduleJobs 类注入由@Component 变为 @Service 。达到预期效果,定时器只启动一次。

package org.gfg.portal.schedule;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gfg.portal.dao.order.OrderFormDao;
import org.gfg.portal.dao.order.OrderSelectedDataDao;
import org.gfg.portal.entity.order.OrderForm;
import org.gfg.portal.entity.order.OrderSelectedData;
import org.gfg.portal.remoteinterface.dps.DpsHadoopServiceRemoting;
import org.gfg.portal.service.DownloadOrderService;
import org.gfg.portal.service.order.IMyOrderService;
import org.gfg.portal.service.order.OrderGuideService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
// 此处 @Component 改为 @Service 
//由于 spring-dispatch.xml 排除了 @Service的加载
//所以只在 spring-datasource.xml 的加载中有效
@Component
public class ScheduleJobs {
   private static final Log logger = LogFactory.getLog(ScheduleJobs.class);
   @Scheduled(cron = "0 0 * * * *")
   public void cleanOutOfDateDownloadLinks() {
      System.out.println("####Cleaning out of date download links");
   }
}

你可能感兴趣的:(java,@Scheduled,spring,定时器)