ScheduledExecutorService从下面的类的关闭方法调用其关闭方法后仍在运行。
我没想到在关机后会看到perioudRun的调用运行shutdown方法运行方法periodicRun——
我该如何确保计划运行被取消?
class test {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
test() {
scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
funcA("periodicRun-");
}
}, 15, 15, TimeUnit.SECONDS);
}
private void funcA(String path) {
LOGGER.info("Running the method " + path)
}
public void shutdown() {
long startTimeMs = System.currentTimeMillis();
scheduler.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!scheduler.awaitTermination(initialTerminationSeconds, TimeUnit.SECONDS)) {
scheduler.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
scheduler.awaitTermination(retryTerminationSeconds,
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
scheduler.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
funcA("shutdown-");
}
}```
您提供的代码无法编译。我做了一些更正和一些假设,它没有编译,下面的代码按预期工作,即"周期性运行"。在调用shutdown()
后不打印:
class Test {
public static void main(String[] args) {
Test test = new Test();
test.test(); // CALL TEST METHOD
Thread t = new Thread(() -> {
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.shutdown(); // CALL SHUTDOWN METHOD
});
t.start();
}
private final int initialTerminationSeconds = 1;
private final int retryTerminationSeconds = 1;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
void test() {
scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
funcA("periodicRun-");
}
}, 15, 15, TimeUnit.SECONDS);
}
private void funcA(String path) {
System.out.println("Running the method " + path);
}
public void shutdown() {
long startTimeMs = System.currentTimeMillis();
scheduler.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!scheduler.awaitTermination(initialTerminationSeconds, TimeUnit.SECONDS)) {
scheduler.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
scheduler.awaitTermination(retryTerminationSeconds, TimeUnit.SECONDS);
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
scheduler.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
funcA("shutdown-");
}
}
由于此代码按预期工作,您的代码中的问题要么是在其他地方,要么是我对您的代码所做的假设和更正不正确。