英文:
How to run a cancellable scheduled task in java
问题
// The kotlin function `delay()` has this specification:
// > * 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].
// I want to achieve the exact functionality using Java. Basically, I need to run
// a function using some delay and this should be cancellable anytime by some given condition.
// I've already gone through [this][1] thread, but most of the answers aren't quite
// the right fit for my scenario.
// [1]: https://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
Please note that the content provided appears to be code-related, which might lose its context when translated without proper understanding. If you have any specific questions or need further assistance, feel free to ask.
英文:
The kotlin function delay()
has this specification:
> * 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].
I want to achieve exact functionality using Java. Basically, I need to run a function using some delay and this should be cancellable anytime by some given condition.
I've already gone through this thread, but most of the answers aren't quite the right fit for my scenario.
答案1
得分: 2
你正在寻找ScheduledExecutorService
。
// 创建调度器
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1);
// 创建要执行的任务
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello");
}
};
ScheduledFuture<?> scheduledFuture =
scheduledExecutorService.schedule(r, 5, TimeUnit.SECONDS);
// 取消任务
scheduledFuture.cancel(false);
当你取消它时,会抛出InterruptedException
异常。
英文:
You are looking for the 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);
when you cancel it an InterruptedException
will be thrown.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论