我想定期执行一个线程来检查某个文件是否准备好上传,并在准备好后立即上传,然后立即停止线程。另外,如果已经过去很长一段时间,我想停止线程,无论文件尚未准备好,但不能在 run 方法本身内部执行此操作。
final ScheduledFuture<?> fileUploadedFuture = scheduler.scheduleAtFixedRate(() -> {
try {
if (fileReady("xyz.txt")) {
uploadFile("xyz.txt")
//cancel fileUploadedFuture and fileUploadedFutureCanceller
}
} catch (Exception e) {
throw new ServiceException(e);
}
}, 0, delay, TimeUnit.SECONDS);
final ScheduledFuture<?> fileUploadedFutureCanceller = scheduler.schedule(() -> {
fileUploadedFuture.cancel(true);
}, 60, TimeUnit.SECONDS);
}
最佳答案
使用 ScheduledThreadPoolExecutor 怎么样?
public class TestExecutor {
private static ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
private static class PushFile implements Runnable {
@Override
public void run() {
if (new File("test.txt").exists()) {
System.out.println("found it!");
exec.shutdown();
} else {
System.out.println("waiting");
}
}
}
private static class ShutMeDown implements Runnable {
@Override
public void run() {
System.out.println("timeout");
exec.shutdown();
}
}
public static void main(String[] args) {
exec.scheduleWithFixedDelay(new PushFile(), 0, 1, TimeUnit.SECONDS);
exec.scheduleWithFixedDelay(new ShutMeDown(), 10, 1, TimeUnit.SECONDS);
}
}
关于java - 定期执行线程并在满足条件或时间结束后停止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44006905/