Scheduled executor: poll for result at fix rate and exit if timeout or result valid

前端 未结 2 1679
陌清茗
陌清茗 2020-12-19 16:11

Problem: I have a requirement to call a dao method at fix rate say every 10 sec, then I need to check if the result is valid if yes exit, else keep on call

2条回答
  •  清歌不尽
    2020-12-19 17:05

    Make it a self-scheduling task. In pseudo code:

    public class PollingTaskRunner {
    
    ...
    CountDownLatch doneWait = new CountDownLatch(1);
    volatile boolean done;
    
    PollingTaskRunner(Runnable pollingTask, int frequency, int period) {
        ...
        endTime = now + period;
        executor.schedule(this, 0);
    }
    
    run() {
    
        try {
            pollingTask.run();
        } catch (Exception e) {
            ...
        }
        if (pollingTask.isComplete() || now + frequency > endTime) {
            done = true;
            doneWait.countDown();
            executor.shutdown();
        } else {
            executor.schedule(this, frequency);
        }
    }
    
    await() {
        doneWait.await();
    }
    
    isDone() {
        return done;
    }
    }
    

    It is not that complicated but add plenty of debug statements the first time you run/test this so you know what is going on. Once it is running as intended, it is easy to re-use the pattern.

提交回复
热议问题