如何在 spring web flux 中编写 cron 作业(计划任务)?
How to write a cron job ( Scheduled task ) in spring web flux?
我正在 spring 网络通量应用程序中实现忘记密码功能,并且我正在发送一个提前 5 分钟过期的 OTP。所以我想通过每 2 秒执行一次 cron 作业来使它们无效。
虽然这是一个 web flux 项目,但我想首先像这样编写一个 hello world 作为 cron 作业来测试。
我在 starter main class 中添加了 @EnableScheduling 并且我写了一个测试 class 之类的。
@Scheduled(cron = "*/2 * * * * *")
public Disposable invalidateOtp(){
return Mono.fromCallable(() -> {
return "Hello";
}).subscribe();
}
但我会说这个方法不会每2秒执行一次。谁能告诉我为什么?
这是一篇很好的文章,介绍如何 运行 使用 cron 表达式或固定速率或固定延迟的计划任务:The @Scheduled Annotation in Spring. This should give you all you need. However, At some point I felt that all options provided in Spring boot were not convinient enough especially for human readability of the params. You have to specify time in milliseconds or with cron-expression which is not very easily readable. So, I wanted to be able specify time like "9m" for 9 minutes or "3h" for 3 hours and so forth. So, I wrote my own background task scheduler that can easily be used with Spring boot. I published it in Open source library called MgntUtils which is written and maintained by me. Here is a Javadoc page that explains my idea and how to use the feature. (This is part of MgntUtils library javadoc) You can get the library as Maven artifact here or on the github(包括 javadoc 和 source-code)。在 github 上,您可以查看包:com.mgnt.lifecycle.management.backgroundrunner.example
。该包包含 2 个计划任务的完整工作示例。如果您下载源代码,您可以 运行 开箱即用,看看它们是如何工作的
我终于找到了答案。我忘记注释我的服务 class @Service。否则spring将找不到任何bean。
我正在 spring 网络通量应用程序中实现忘记密码功能,并且我正在发送一个提前 5 分钟过期的 OTP。所以我想通过每 2 秒执行一次 cron 作业来使它们无效。
虽然这是一个 web flux 项目,但我想首先像这样编写一个 hello world 作为 cron 作业来测试。
我在 starter main class 中添加了 @EnableScheduling 并且我写了一个测试 class 之类的。
@Scheduled(cron = "*/2 * * * * *")
public Disposable invalidateOtp(){
return Mono.fromCallable(() -> {
return "Hello";
}).subscribe();
}
但我会说这个方法不会每2秒执行一次。谁能告诉我为什么?
这是一篇很好的文章,介绍如何 运行 使用 cron 表达式或固定速率或固定延迟的计划任务:The @Scheduled Annotation in Spring. This should give you all you need. However, At some point I felt that all options provided in Spring boot were not convinient enough especially for human readability of the params. You have to specify time in milliseconds or with cron-expression which is not very easily readable. So, I wanted to be able specify time like "9m" for 9 minutes or "3h" for 3 hours and so forth. So, I wrote my own background task scheduler that can easily be used with Spring boot. I published it in Open source library called MgntUtils which is written and maintained by me. Here is a Javadoc page that explains my idea and how to use the feature. (This is part of MgntUtils library javadoc) You can get the library as Maven artifact here or on the github(包括 javadoc 和 source-code)。在 github 上,您可以查看包:com.mgnt.lifecycle.management.backgroundrunner.example
。该包包含 2 个计划任务的完整工作示例。如果您下载源代码,您可以 运行 开箱即用,看看它们是如何工作的
我终于找到了答案。我忘记注释我的服务 class @Service。否则spring将找不到任何bean。