tags:

views:

72

answers:

2

I'm looking for a way to have spring beans registering themselves to a job processor bean who in turn will execute the registered beans on a schedule.

I'm hoping that the bean would just have to implement an interface and by some spring mechanism get registered to the job processor bean. Or alternatively inject the job processor bean into the beans and then somehow the job processor bean can keep track of where it's been injected.

Any suggestions appreciated, it might be that spring is not the tool for this sort of thing?

+1  A: 

Use a spring context something like this:

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&gt;

    <!--Scans the classpath for annotated 
         components @Component, @Repository, 
         @Service, and @Controller -->

    <context:component-scan base-package="org.foo.bar"/>


    <!--Activates @Required, @Autowired, 
        @PostConstruct, @PreDestroy 
         and @Resource-->
    <context:annotation-config/>
</beans>

And define a pojo like this:

@Component
public class FooBar {}

And inject like this:

@Component
public class Baz {
    @Autowired private FooBar fooBar;
}
Paul McKenzie
A: 

Spring has a powerful abstraction layer for Task Execution and Scheduling.

In Spring 3, there are also some annotations that you can use to mark bean methods as scheduled (see Annotation Support for Scheduling and Asynchronous Execution)

You can let a method execute in a fixed interval:

@Scheduled(fixedRate=5000)
public void doSomething() {
    // something that should execute periodically
}

Or you can add a CRON-style expression:

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    // something that should execute on weekdays only
}

Here's the XML code you'll need to add (or something similar):

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>

Used together with

<context:component-scan base-package="org.foo.bar"/>
<context:annotation-config/>

as described by PaulMcKenzie, that should get you where you want to go.

seanizer
Thanks will try it!
GeorgeOscarBluth