How to execute jobs just after spring loads application context?
I want to run some开发者_如何学Go jobs just after loading the Spring context but I do not know how to do this.
Do you have any idea how to do that?Another possibility would be to register a listener to application context events (). Basically it's the same as skaffman's solution, just implement:
org.springframework.context.ApplicationListener<org.springframework.context.event.ContextRefreshedEvent>
instead of Lifecycle. It has only one method instead of three. :-)
If you want run a job after Spring's context start, then you can use the ApplicationListener
and the event ContextRefreshedEvent
.
public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
// do what you want - you can use all spring beans (this is the difference between init-method and @PostConstructor where you can't)
// this class can be annotated as spring service, and you can use @Autowired in it
}
}
You can write a bean class that implements the org.springframework.context.Lifecycle
interface. Add this bean to your context, and the start()
method will be invoked by the container once that context has finished starting up.
Use the @PostConstruct
annotation. Than you can combine any job properties and guarantee to run your method on the load context.
thank you all for your reply. In fact I missed a little detail in my question, I wanted to run Quartz Job just after loading the application context.. I tried the solution stakfeman, but I had some problems running the Quartz Jobs. Finally I found that solution: Use Quartz within Spring ,here is the code:
<!--
===========================Quartz configuration====================
-->
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="processLauncher" />
<property name="targetMethod" value="execute" />
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<!-- see the example of method invoking job above -->
<property name="jobDetail" ref="jobDetail" />
<!-- 10 seconds -->
<property name="startDelay" value="10000" />
<!-- repeat every 50 seconds -->
<property name="repeatInterval" value="50000" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
</list>
</property>
</bean>
thank you again for the help and I apologize if the question was not very clear ':(
精彩评论