简体   繁体   English

如何验证ScheduledExecutorService已启动?

[英]How verify a ScheduledExecutorService has started?

Description 描述

A task A is running, that can last from 2s to 60+s. 任务A正在运行,可能持续2s到60 + s。

While A is running, I scheduled a ExecutorService that after 10s (delay), would print "running" every 5s (fixed rate). 当A运行时,我安排了一个ExecutorService,该服务在10s(延迟)后每5s(固定速率)打印一次“ running”。

ScheduledExecutorService scheduleNotifications = Executors
        .newSingleThreadScheduledExecutor();
scheduleNotifications.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        System.out.println("A is running");
    }
}, 10, 5, TimeUnit.SECONDS);

Once A is done, I wish to print "A is done." 完成A后,我希望打印“ A完成”。 but only if my ScheduledExecutorService task has started , meaning it printed "running" at least once. 但仅当我的ScheduledExecutorService任务已启动时 ,这意味着它至少打印一次“正在运行”。

  • If A finished before 10s, I do not print anything. 如果A在10秒钟之前完成,我什么都不打印。
  • If A takes more than 10s, I print "running" every 5s and then "done" once A is finished. 如果A花费的时间超过10s,则我每5s打印一次“ running”,然后在A完成后“完成”打印。

How could I do that without using a boolean flag inside the schduled runnable . 我如何才能做到这一点,而无需在schduled runnable使用布尔标志。 Is there a way to check that my service started? 有没有办法检查我的服务是否启动?

ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);
scheduler.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        System.out.println("A is running");
    }
}, 10, 5, TimeUnit.SECONDS);

Thread.sleep(20000);
scheduler.shutdown();
if (scheduler.getCompletedTaskCount() > 0) {
    System.out.println("A is done.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM