java - 仅调度线程一次。

标签 java multithreading thread-safety threadpool

如何修复我的线程以将线程的初始延迟安排为 2 分钟并且不再安排它。 (即仅安排一次)

@Scheduled(fixedDelay = 5000)
public void myJob() {
     Thread.sleep(12000);
}

最佳答案

您可以使用ScheduledExecutorService在这种情况下。它是一个 ExecutorService,可以安排命令在给定的延迟后运行,或定期执行。

ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit)

Creates and executes a ScheduledFuture that becomes enabled after the given delay.

callable - the function to execute
delay - the time from now to delay execution
unit - the time unit of the delay

  ScheduledExecutorService service = null;

    service = Executors.newScheduledThreadPool(1);

    service.schedule(() -> {
        myMethodNameWhichIWantToExecute();
    }, 2, TimeUnit.MINUTES);

    if (service != null) service.shutdown();

关于java - 仅调度线程一次。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601860/

相关文章:

java - 在 log.d 中获取 json 响应,但不在应用程序内获取(包含代码)

java - 在 SimpleDateFormat 上同步与克隆

multithreading - 如何在单个线程中执行一些Clojure future ?

c# - 为什么我的并行任务代码无法达到100%的CPU使用率?

multithreading - 实现线程安全日志记录

java - 无法解决与Java Threads相关的教科书示例

c++ - 指向对象初始化线程安全的静态指针

java - 是否可以扫描 HBase 中某个日期之后更改的行?

java - Hazelcast 客户端 : how to set the port

java - Java中如何求nxn矩阵每一列的和?