code: private void cleanup(boolean atStartup) {
          boolean allTasksIdle = false;
          while (!allTasksIdle) {
              int activeCount = 0;
              for (Task task: taskDao.listTasks()) {
                  if (!task.getState().equals(Task.IDLE)) {
                      activeCount++;
                      if (!task.getState().equals(Task.CANCELING)) {
                          logger.info("Auto-canceling task " + task.getId() + " (" + task.getName() + ")");
                          taskDao.setTaskState(task.getId(), Task.CANCELING);
                          task.setState(Task.CANCELING);
                      }
                      if (atStartup) {
                          // We're cleaning up after an unclean shutdown.
                          // Since the TaskRunner isn't actually running, we make
                          // the direct call here to clean up the state in the
                          // database, marking it as canceled.
                          taskCanceled(task);
                      } else {
                          // In the normal case, the TaskRunner is running in a
                          // separate thread and we just need to request that
                          // it cancel at the next available opportunity.
                          cancelTask(task);
                      }
                  }
              }
              if (activeCount == 0 || atStartup) {
                  allTasksIdle = true;
              } else {
                  logger.info("Waiting for " + activeCount + " task(s) to go idle.");
                  sleepSeconds(1);
              }
          }
      }
docs: Cancel any non-idle tasks and wait for them to go idle