@Override
    public void cancel() {
        synchronized (monitor) {
            if (!periodicExecutionCancellation.isPresent()) {
                throw new IllegalStateException("setPeriodicExecutionCancellationCallback has not been called before cancel");
            }

            cancelled = true;
            if (running) return;
        }

        runlet.close();
        periodicExecutionCancellation.get().run();
    }
@Test
    public void testCancelWhileRunning() {
        // halt execution in runlet
        runlet.shouldWaitInRun(true);
        executor.runAsync();
        runlet.waitUntilInRun();
        assertEquals(3, runlet.getRunsStarted());
        assertEquals(2, runlet.getRunsCompleted());
        assertTrue(executor.isExecutionRunning());
        assertFalse(runlet.isClosed());

        // Cancel now
        cancellable.cancel();
        assertTrue(executor.isExecutionRunning());
        assertFalse(runlet.isClosed());

        // Complete the runlet.run(), and verify the close and executor cancellation takes effect
        runlet.shouldWaitInRun(false);
        executor.waitUntilRunCompleted(3);
        assertFalse(executor.isExecutionRunning());
        assertTrue(runlet.isClosed());

        // Ensure a spurious run is ignored.
        executor.runToCompletion(4);
        assertEquals(3, runlet.getRunsStarted());
    }