Spring Scheduler不起作用

use*_*882 19 spring scheduling spring-mvc

我的Spring基于注释的任务调度程序有问题 - 我无法使其工作,我在这里看不到任何问题...

应用程序的context.xml

<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />
Run Code Online (Sandbox Code Playgroud)

@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 <<<");
    }

}
Run Code Online (Sandbox Code Playgroud)

ahl*_*hll 40

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

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

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

Run Code Online (Sandbox Code Playgroud)

  • 添加@EnableScheduling 节省了我很多时间。非常感谢 (3认同)

Ser*_*uşu 23

如果您想使用task:annotation-driven方法并且@Scheduled注释不起作用,那么您很可能context:component-scan在上下文中错过了xml.如果没有这一行,spring就无法猜测在哪里搜索注释.

<context:component-scan base-package="..." />
Run Code Online (Sandbox Code Playgroud)

  • application.conf 是否有等效的 spring-boot ? (3认同)

Bab*_*yan 12

发生这种情况是因为默认情况下 Spring 延迟初始化 bean。

通过放置此注释禁用 bean 的延迟初始化

@Lazy(false)
Run Code Online (Sandbox Code Playgroud)

在您的@Component.


小智 8

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


use*_*882 5

我终于找到了解决办法。

应用程序上下文.xml

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

<task:scheduled-tasks>
    <task:scheduled ref="schedulingTest" method="test" cron="* * * * * ?"/>
</task:scheduled-tasks>
Run Code Online (Sandbox Code Playgroud)

以及test()没有注释的方法。该方法每秒运行一次并且运行良好。


pas*_*upa 5

配置调度程序后,在主类中添加@EnableScheduling**在此处输入图片描述**