gpt4 book ai didi

java - Spring中@Scheduled方法中的Thread.sleep

转载 作者:行者123 更新时间:2023-11-30 02:10:38 24 4
gpt4 key购买 nike

我有一个计划每 X 毫秒运行一次的方法。

此方法正在新线程中启动新方法。

尽管如此,我想在再次计数之前延迟此方法。

这是我的代码:

@Scheduled(fixedRate = RATE_IN_MS)
public void myMethod(){
new Thread(() -> method()).start();
Thread.sleep(RATE_IN_MS);
}

问题是行为并不像我想要的那样。

这是当前的行为:

  1. 启动 RATE_IN_MS myMethod 后。
  2. method() 开始在不同的线程中运行。
  3. 启动 RATE_IN_MS myMethod 后。

问题:为什么我的 sleep 方法没有延迟 myMethod 的下一次启动? RATE_IN_MS(通过fixedDelay)+ RATE_IN_MS(因为Thread.sleep(RATE_IN_MS)需要是它们之间的实际延迟。

我在这里缺少什么?

谢谢!

最佳答案

我创建了这个运行示例供您引用。执行延迟是在 spring 配置文件中配置的,您可以根据需要更改它。

package com.myprgm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class JobSchdulingServc {
@Value("${com.executionDelay}")
private long executionDelay; // in milliseconds,mention in sping property file
@Autowired
TaskScheduler taskScheduler;

@Bean
public TaskScheduler poolScheduler() {
return new ThreadPoolTaskScheduler();
}

private void stopSceduling(boolean terminateJob) {
((ThreadPoolTaskScheduler) taskScheduler).shutdown();
if (terminateJob) {
System.exit(1);
}

}
public void scheduleMyJob() {
taskScheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
someServiceimpl.generateMyDataAndSendInEveryMilliSeconds(); // service you want to execute after
// specified executionDelay
} catch (Exception e) {
stopSceduling(true);
}
}

}, executionDelay);
}

}

关于java - Spring中@Scheduled方法中的Thread.sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com