java Spring 计划任务不会在应用程序启动时启动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42246301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Scheduled task does not start on application startup
提问by v1shnu
I have a @Scheduled
task in my application which is setup using CRON
and run every 4 hours. The problem I face is that the CRON
job does not start immediately after application startup but it starts only 4 hours after the application startup.
@Scheduled
我的应用程序中有一项任务,该任务设置使用CRON
并每 4 小时运行一次。我面临的问题是该CRON
作业不会在应用程序启动后立即启动,而是在应用程序启动后仅 4 小时启动。
I tried to use a @PostConstruct
method inside the task to invoke it, but that results in an error due to an uninitialized Spring context.
我尝试@PostConstruct
在任务中使用一个方法来调用它,但由于未初始化的 Spring 上下文导致错误。
Please tell me how I can make the Scheduled task run immediately on application deployment and then on every 4 hours after the deployment.
请告诉我如何在应用程序部署时立即运行计划任务,然后在部署后每 4 小时运行一次。
EDIT:
I would not use a @PostConstruct
since my scheduled method depends on other Beans , which are not initialized when this PostConstruct method runs for some reason.
编辑:
我不会使用 a@PostConstruct
因为我的计划方法依赖于其他 Beans ,当这个 PostConstruct 方法由于某种原因运行时没有初始化。
回答by Tomas F.
By 0 */4 * * * you specify "At minute 0 past every 4th hour (0:00, 4:00, 8:00 etc.)", which is not at startup time and then every 4 hours as I think you want. You can specify initial delay and rate by:
通过 0 */4 * * * 您指定“每 4 小时后的第 0 分钟(0:00、4:00、8:00 等)”,这不是在启动时间,然后是我认为的每 4 小时想。您可以通过以下方式指定初始延迟和速率:
@Scheduled(initialDelay=0, fixedRate=4*60*60*1000)
If you are worried about hard-coded values, you can still provide config value:
如果您担心硬编码值,您仍然可以提供配置值:
@Scheduled(initialDelay=0, fixedRateString = "${some.config.string}")
回答by Murugapandian Ramaiah
I had @EnableScheduling
in my app config. I had
@Scheduled(fixedDelay=5000)
in my scheduled task class. Even then it didn't work.
我@EnableScheduling
在我的应用程序配置中有。我
@Scheduled(fixedDelay=5000)
在我的计划任务课上。即使那样也没有奏效。
I added @Service
to my scheduled task class and everything worked fine.
我添加@Service
到我的计划任务类,一切正常。
回答by Dherik
If is not possible to use initialDelay
attribute with the cron
rule and your intention is execute this Job after every restart, you can implement a CommandLineRunner
on your application class:
如果无法将initialDelay
属性与cron
规则一起使用,并且您的意图是在每次重新启动后执行此作业,您可以CommandLineRunner
在您的应用程序类上实现:
@SpringBootApplication
public class MyApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Autowired
private TaskService taskService;
@Override
public void run(final String... args) throws Exception {
taskService.run();
}
}
It's not the best strategy, but works.
这不是最好的策略,但有效。
回答by px06
I'm not sure if you have tried this but you can use @Scheduled
with an initialDelay
我不知道,如果你已经尝试过这一点,但你可以用@Scheduled
用initialDelay
For fixed-delay and fixed-rate tasks, an initial delay may be specified indicating the number of milliseconds to wait before the firstexecution of the method.
对于固定延迟和固定速率任务,可以指定初始延迟,指示在第一次执行该方法之前等待的毫秒数。
@Scheduled(initialDelay=0, fixedRate=5000)
public void doSomething() {
// something that should execute periodically
}
I assume this will execute your scheduled method when the application is run.
我假设这将在应用程序运行时执行您的计划方法。
回答by Monzurul Haque Shimul
Instead of cron inside @Scheduled, use fixedRate like below. By default initialDelay is -1, which will start immediately or you can set 0.
而不是 @Scheduled 中的 cron,使用如下所示的 fixedRate。默认initialDelay 是-1,它会立即开始或者你可以设置为0。
@Scheduled(fixedRate=4*60*60*1000)
public void test() {
System.out.println("helloworld");
}
回答by Andrei Balici
Just specify the method you want to run in the init_method
attribute of the bean.
只需init_method
在 bean的属性中指定要运行的方法即可。
Java config: @Bean(init_method="methodWhichStartsTask")
Java配置: @Bean(init_method="methodWhichStartsTask")
XML config: <bean id="someId" class="com.example.Clazz" init-method="methodWhichStartsTask"/>
XML 配置: <bean id="someId" class="com.example.Clazz" init-method="methodWhichStartsTask"/>
This will invoke the method just after the bean is properly initialized and if the method is scheduled, then it will be called afterwards every 4 hours.
这将在 bean 正确初始化后立即调用该方法,如果该方法已调度,则此后每 4 小时将调用一次。
回答by Vishal Patel
I was having the same situation. I need to run cron scheduler every 1st day of the month and also when the application starts.
我遇到了同样的情况。我需要在每个月的第一天以及应用程序启动时运行 cron 调度程序。
This is how I achieved using ApplicationListener.
这就是我使用 ApplicationListener 实现的方式。
import org.springframework.context.ApplicationListener;
import org.springframework.boot.context.event.ApplicationReadyEvent;
@Component
public class ApplicationReadyListner implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// callYourTask();
}
}
回答by M2E67
user @EnableScheduling annotation on your class which contains you1 scheduled method:
您的类上的用户 @EnableScheduling 注释,其中包含您 1 个预定的方法:
see spring document:
参见弹簧文档:
To enable support for @Scheduled and @Async annotations add @EnableScheduling and @EnableAsync to one of your @Configuration classes:
要启用对 @Scheduled 和 @Async 注释的支持,请将 @EnableScheduling 和 @EnableAsync 添加到您的 @Configuration 类之一:
@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}
link : https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
链接:https: //docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html