|
|
@@ -0,0 +1,51 @@
|
|
|
+package com.skyversation.xjcy.util;
|
|
|
+
|
|
|
+import java.util.concurrent.ExecutorService;
|
|
|
+import java.util.concurrent.Executors;
|
|
|
+import java.util.concurrent.atomic.AtomicBoolean;
|
|
|
+
|
|
|
+public class RobustTaskExecutor {
|
|
|
+ private final AtomicBoolean isRunning = new AtomicBoolean(false);
|
|
|
+ private final AtomicBoolean needsRerun = new AtomicBoolean(false);
|
|
|
+ private final Runnable task;
|
|
|
+ private final ExecutorService executor;
|
|
|
+
|
|
|
+ public RobustTaskExecutor(Runnable task) {
|
|
|
+ this.task = task;
|
|
|
+ this.executor = Executors.newSingleThreadExecutor();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void run() {
|
|
|
+ // 如果任务正在执行,设置需要重新执行的标志
|
|
|
+ if (isRunning.get()) {
|
|
|
+ needsRerun.set(true);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 获取执行权
|
|
|
+ if (isRunning.compareAndSet(false, true)) {
|
|
|
+ executor.submit(this::executeTask);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void executeTask() {
|
|
|
+ try {
|
|
|
+ // 执行实际任务
|
|
|
+ task.run();
|
|
|
+ } finally {
|
|
|
+ // 任务执行完毕,检查是否需要重新执行
|
|
|
+ boolean shouldRerun = needsRerun.getAndSet(false);
|
|
|
+ isRunning.set(false);
|
|
|
+
|
|
|
+ // 如果需要重新执行,则再次调用run方法
|
|
|
+ if (shouldRerun) {
|
|
|
+ run();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void shutdown() {
|
|
|
+ executor.shutdown();
|
|
|
+ }
|
|
|
+
|
|
|
+}
|