如何 运行 java 中的可取消计划任务

How to run a cancellable scheduled task in java

kotlin 函数 delay() 具有以下规范:

  • Delays coroutine for a given time without blocking a thread and resumes it after a specified time. * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException].

我想使用 Java 实现确切的功能。基本上,我需要 运行 一个使用一些延迟的函数,这应该可以在某些给定条件下随时取消。

我已经完成了 this 话题,但大多数答案都不太适合我的情况。

您正在寻找 ScheduledExecutorService

 // Create the scheduler
    ScheduledExecutorService scheduledExecutorService = 
     Executors.newScheduledThreadPool(1);
    // Create the task to execute
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello");
        }
    };
    ScheduledFuture<?> scheduledFuture =
        scheduledExecutorService. schedule(r, 5, TimeUnit.SECONDS);
  
    // Cancel the task
    scheduledFuture.cancel(false);

当您取消它时,将抛出 InterruptedException