java - 如何在不同时间后执行任务

标签 java multithreading

Class A 
{
 long x;
 method1()
  {
   x = current time in millisecs;
  }
 task()//want to run this after (x+30) time
}

我需要在 (x+30) 之后运行 task() 。 x 可能会有所不同。如果调用 method1,则任务计划在当前时间 30 秒后运行,但在这 30 时间段内,如果再次调用 method1,那么我想取消之前的任务调用,并希望在当前时间 30 秒后安排对任务的新调用时间。我应该如何创建这种类型的调度程序或任务?

查看了 scheduledthreadpoolexecutor API 但没有找到这种类型的调度程序。

最佳答案

你问了 2 个问题:

1。如何安排任意延迟的任务?

您可以使用 schedule 之一methodsjava.util.concurrent.ScheduledThreadPoolExecutor

int delay = System.currentTimeMillis + 30;
myScheduledExecutor.schedule(myTask, delay, TimeUnit.MILLISECONDS);

2。如何取消已在运行的任务?

您通过调用 cancel 取消任务在 Future 上这是从您调用的 schedule 方法返回的。

if (!future.isDone()){
    future.cancel(true);
}
future = myScheduledExecutor.schedule(myTask, delay, TimeUnit.MILLISECONDS);

关于java - 如何在不同时间后执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283908/

相关文章:

java - 为什么要在 Java 中使用嵌套的 InvokeLater 调用?

linux - 寻找具有操作系统调度程序支持的 Linux 线程池 api

java - 如何避免 spring data neo4j 获取父节点作为树数据结构中子集合的成员?

java - sql.date 与 util.date

java - 使用 Eclipse 和 OSGi 将类动态加载到 Java 类路径

java - Spring RestTemplate 解析具有可变键名的 JSON 对象

java - char 数组值未更改为大写

android - 在不访问 Activity 的情况下在 Android 的主线程上执行代码?

JAVA:调度线程工作的最佳方式是什么?

c# - 为什么 volatile 和 MemoryBarrier 不阻止操作重新排序?