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

问题描述

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

  • 将协同程序延迟给定时间,而不会阻塞线程,并且 在指定的时间后恢复它。 *此暂停功能可取消。 *如果当前协程的[作业]被取消或 此挂起功能正在等待时完成,此功能* 立即使用[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