英文:
Java Spring-BOOT: main-loop beside HTTP-handler
问题
我从Spring BOOT开始。
public class App
{
public static void main(String[] args) throws Exception
{
System.out.println("--------------------");
SpringApplication.run(App.class, args);
for (;;) // 我的主循环
{
// 永久执行某些操作
Thread.sleep(10000);
}
}
}
除了HTTP处理组件,我还想有一个主循环(例如,用于在HTTP之外执行任务)。
* 这种设计中的循环是实现此目的的最佳方式吗?
我正在使用配置绑定(@Value和@ConfigurationProperties)。
* 如何在我的主循环中获取那些信息?我不能使用静态变量来做到这一点。
英文:
I am starting with Spring BOOT.
public class App
{
public static void main (String [] args) throws Exception
{
System.out.println ("--------------------");
SpringApplication.run (App.class, args);
for (;;) // my main loop
{
// do something permanently
Thread.sleep (10000);
}
}
}
Beside the HTTP-handler-conponents I have I like to have a main-loop (e.g. for doing tasks beside HTTP).
- Is this design with the loop the best way to do that?
I am using configuration-binding (@Value and @ConfigurationProperties too).
- How can I get that information in my main-loop? I can not do it with static variables.
答案1
得分: 3
不要在您的应用程序类中执行类似的操作。
只需定义一个Spring Bean,并注释一个包含您想要定期执行的任何逻辑的函数,并使用@Scheduled进行注释。
欲了解更多信息,请参阅以下内容:https://www.baeldung.com/spring-scheduled-tasks
英文:
Dont do anything like that in your Application class.
Just define a spring bean and annotate a function that contains whatever logic you want to have performed regularly and annotate is with an @Scheduled.
Have a look at the following for more information: https://www.baeldung.com/spring-scheduled-tasks
答案2
得分: 3
参见scheduler spring文档。简要地:
在启动器/配置中添加@EnableScheduling:
@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
示例调度器组件:
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 10000)
public void reportCurrentTime() {
// do anything
}
}
英文:
See scheduler spring doc. Briefly:
Add @EnableScheduling to starter/config:
@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
example scheduler component:
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 10000)
public void reportCurrentTime() {
// do anything
}
}
答案3
得分: 1
我认为这不会是更好的设计。
如果你想要执行非HTTP任务,我建议创建一个新的Bean,然后使用 @Scheduled 注解,并可以指定你想要执行任务的时间。
@Component
public class YourTask {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
// 你的任务
}
}
英文:
I dont think this would be the better design.
If you wan to do the non HTTTP task then then i would recommend creating new bean and using @Scheduled and can specify the time when you want to do it.
@Component
public class YourTask{
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
//your task
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论