在WAR中使用Spring

时间:2012-09-07 11:33:40

标签: spring scheduled-tasks

我使用Spring 3 TaskScheduler做了jar应用程序。我用main方法运行这个应用程序:

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

是否可以在Web应用程序(war文件)中运行此jar,main方法?如何在web.xml中运行它。

非常感谢

2 个答案:

答案 0 :(得分: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方法中那样手动执行此操作。

答案 1 :(得分:0)

如果你需要在战争中使用简单的调度程序(使用spring框架),你也可以这样做:

(在Spring中,“@ PostConstruct”将初始化调度程序 - 因此不需要main方法)

    @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;

        }

    }
相关问题