如何在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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...