2012-09-07 52 views
1

我使用Spring 3 TaskScheduler做了jar應用程序。我運行這個應用程序的主要方法:在WAR中使用Spring

public static void main(String[] args) { 
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); 
    ctx.load("classpath:scheduler-app-context.xml"); 
    ctx.refresh(); 
    while (true) { 
    // ... 
    } 
    // ... 
} 

請問可能運行這個jar,主要方法在web應用程序(戰爭文件)?如何在web.xml中運行這個。

非常感謝

回答

0

做這樣的事情在你的web.xml

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:scheduler-app-context.xml</param-value> 
</context-param> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

這將實例從XML文件中的Spring上下文。因此,您無需像在main方法中那樣手動執行此操作。

0

如果您需要在戰爭中簡單的調度器(帶彈簧框架),你也可以做這樣的事情:

(Spring中的「@PostConstruct」將初始化調度 - 所以沒有必要對主要方法)

@Component 
    public class Scheduler { 

     private static final Logger LOG = LoggerFactory.getLogger(Scheduler.class); 


     @PostConstruct 
     private void initializeTenSecSchedule() { 

      final List<Runnable> jobs = new ArrayList<Runnable>(); 

      jobs.add(doSomeTestLogs()); 
      jobs.add(doSomeTestLogs2()); 

      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(jobs.size()); 

      for(Runnable job : jobs){ 

       scheduler.scheduleWithFixedDelay(job, 10, 10, SECONDS); 

      } 

     } 

     /** 
     * ---------------------some schedule tasks-------------------------- 
     */ 

     private Runnable doSomeTestLogs(){ 

      final Runnable job = new Runnable() { 
       public void run() { 

        LOG.debug("== foo SCHEDULE a", 1); 
        System.out.println("Method executed at every 10 seconds. Current time is :: "+ new Date()); 

       } 
      }; 

      return job; 

     } 

     private Runnable doSomeTestLogs2(){ 

      final Runnable job = new Runnable() { 
       public void run() { 

        LOG.debug("== foo SCHEDULE b", 1); 
        System.out.println("Method executed at every 10 seconds. Current time is :: "+ new Date()); 

       } 
      }; 

      return job; 

     } 

    }