简体   繁体   中英

How verify a ScheduledExecutorService has started?

Description

A task A is running, that can last from 2s to 60+s.

While A is running, I scheduled a ExecutorService that after 10s (delay), would print "running" every 5s (fixed rate).

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." but only if my ScheduledExecutorService task has started , meaning it printed "running" at least once.

  • If A finished before 10s, I do not print anything.
  • If A takes more than 10s, I print "running" every 5s and then "done" once A is finished.

How could I do that without using a boolean flag inside the 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.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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