Spring Scheduler不起作用。

32
我有一个使用Spring注解的定时任务调度的问题 - 我无法让它工作,我在这里没有看到任何问题...
应用程序上下文XML文件
<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />

豆子

@Service
public final class SchedulingTest {

    private static final Logger logger = Logger.getLogger(SchedulingTest.class);

    @Scheduled(fixedRate = 1000)
    public void test() {
        logger.debug(">>> Scheduled test service <<<");
    }

}

我没有收到任何错误信息,而我期望记录“>>>计划测试服务<<<”的消息,但这并没有发生... - user219882
1
你的日志记录器配置正确了吗?日志级别设置正确了吗? - Péter Török
14个回答

80

@Configuration注解(非 XML 配置)用于注释驱动任务的Spring

只需在WebMvcConfig类上添加@EnableScheduling即可


    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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


5
添加 @EnableScheduling 大大节省了我的时间。非常感谢。 - Débora

27
如果您想使用task:annotation-driven的方式并且您的@Scheduled注释无法工作,则您很可能在您的上下文XML中错过了context:component-scan。没有这行,Spring就不能猜测要在哪里搜索您的注释。
<context:component-scan base-package="..." />

3
有没有类似于application.conf的Spring Boot等价配置文件? - Pwnstar

14

这是因为Spring默认会对bean进行延迟初始化。

通过添加以下注解来禁用bean的延迟初始化:

@Lazy(false)

在你的@Component之上。


10

对于我来说,在Spring 5中有效的解决方案是,我必须将@Component添加到具有@Scheduled注释方法的类中。


8
在配置完调度程序之后,在您的主类中添加@EnableScheduling**输入图片说明**

5

我终于找到了一个解决方案。

application-context.xml

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

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

没有注释的test()方法。这会每秒运行该方法,并且运行得非常完美。


1
这肯定能够运行,因为你已经放弃了“task:annotation-driven”方法。关于缺失的一行代码,你可以看看其他答案。祝好! - Serkan Arıkuşu

3
我的解决方法是在applicationContext.xml中添加以下内容:
<task:annotation-driven/>

使用以下schemaLocation:

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

3

1
我必须更新我的dispatcher-servlet.xml文件,其中包含:
<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定义:

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

1

你还应该检查该bean的lazy-init属性是否为false,或在beans中使用default-lazy-init="false"

这解决了我的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接