Spring Scheduler does not work

柔情痞子 提交于 2019-12-05 00:06:37

If you want to use task:annotation-driven approach and your @Scheduled annotation is not working, then you most probably missed context:component-scan in your context xml. Without this line, spring cannot guess where to search for your annotations.

<context:component-scan base-package="..." />
ahll

Spring @Configuration (non-xml configuration) for annotation-driven tasks

Just add @EnableScheduling on you WebMvcConfig class

@Configuration
@EnableWebMvc
@EnableAsync
@EnableScheduling
public class WebMvcConfig extends WebMvcConfigurerAdapter {
   /** Annotations config Stuff ... **/
}

I finally found a solution.

application-context.xml

<bean id="schedulingTest" class="...SchedulingTest" />

<task:scheduled-tasks>
    <task:scheduled ref="schedulingTest" method="test" cron="* * * * * ?"/>
</task:scheduled-tasks>

and the test() method without the annotation. This runs the method every second and works perfectly.

Hazhir

if you have dispatcher-servlet.xml move your configuration there. it worked for me and i have left a comment in this article: https://stackoverflow.com/a/11632536/546130

This is happening because by default Spring lazy initializes the beans.

Disable lazy initialization for the bean by placing this annotation

@Lazy(false)

on top of your @Component.

You should also check lazy-init to be false for that bean or use default-lazy-init="false" in beans.

That solved my problem.

The solution for me was to add in the applicationContext.xml:

<task:annotation-driven/>

with the following schemaLocation:

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd

We had the following reason: Service needed an interface (due to Transaction annotation) - IDE added this tx annotation also to interface. But @Scheduled was in implementing service class - and Spring ignored it since it thought that only annotations exist on the interface. So be careful to only have annotations on implementing classes!

vishsodhani

I had to update my dispatcher-servlet.xml with

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task-4.3.xsd"></beans>

Bean definition below:

<bean id="scheduledTasks" class="com.vish.services.scheduler.ScheduledTasks"></bean>

For me the solution that worked in Spring 5 was that I had to add @Component to the class having @Scheduled annotated methods.

Just add @EnableScheduling at any spring boot configuration class annotated with @Configuration and for the method that run the schedule job add @Scheduled annotation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!