Schedule a worker for shutdown. Will finish processing the current job
and when the timeout interval is reached, the worker will shut down.
509978
public function shutdown()
    {
        $this->shutdown = true;
        $this->redis->hmset(self::redisKey($this), 'shutdown', true);

        Event::fire(Event::WORKER_SHUTDOWN, $this);
    }
671317
def shutdown(self):
		
		with self.lock:
			self.pool.inqueue.put(StopIteration)   # Stop the pool workers
			self.waitqueue.put(StopIteration)      # Stop the input_feeder
			_iterqueue(self.waitqueue) >> item[-1] # Exhaust the waitqueue
			self.closed = True
		self.join()
1045866
@Override
  protected void shutDown() throws Exception {
    this.scheduledExecutor.shutdown();
    this.scheduledExecutor.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.SECONDS);
  }
600171
def start_worker(
            self):
        
        # Start a worker thread responsible for sending logs
        if not self.is_shutting_down(shutdown_event=self.shutdown_event) \
                and self.sleep_interval > 0.1:
            self.processes = []
            self.debug_log(
                'start_worker - start multiprocessing.Process')
            p = multiprocessing.Process(
                target=self.perform_work,
                args=(
                    self.queue,
                    self.shutdown_event,
                    self.shutdown_ack,
                    self.already_done))
            p.daemon = True
            p.start()
            self.processes.append({
                'process': p,
                'shutdown_event': self.shutdown_event,
                'shutdown_ack_event': self.shutdown_ack,
                'already_done_event': self.already_done
            })
            self.debug_log(
                'start_worker - done')
241605
def _scheduleRestart(self,
                         when: Union[datetime, str],
                         failTimeout) -> None:
        
        logger.info("{}'s restarter processing restart"
                    .format(self))
        if isinstance(when, str):
            when = dateutil.parser.parse(when)
        now = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())

        logger.info(
            "Restart of node '{}' has been scheduled on {}".format(
                self.nodeName, when))

        ev_data = RestartLogData(when)
        self._actionLog.append_scheduled(ev_data)

        callAgent = partial(self._callRestartAgent, ev_data,
                            failTimeout)
        delay = 0
        if now < when:
            delay = (when - now).total_seconds()
        self.scheduledAction = ev_data
        self._schedule(callAgent, delay)
1075741
function Stopping(worker, startedAt) {
    var spec = worker.spec;
    this.worker = worker;
    this.nextState = null;
    this.isDebugging = false;
    this.startedAt = startedAt;
    this.stopRequestedAt = Date.now();
    this.forceStopHandle = null;
    this.forceStopAt = null;
    this.forcedStop = false;
    this.forceStopDelay = spec.forceStopDelay;

    // Schedule a forceful shutdown if graceful shutdown does not complete in a
    // timely fashion.
    if (this.forceStopDelay < Infinity) {
        this.forceStopAt = Date.now() + this.forceStopDelay;
        this.forceStopHandle = setTimeout(
            this.handleForceStopTimeout.bind(this),
            this.forceStopDelay
        );
    }
}
730883
def _shutdown_proc(p, timeout):
  """"""
  freq = 10  # how often to check per second
  for _ in range(1 + timeout * freq):
    ret = p.poll()
    if ret is not None:
      logging.info("Shutdown gracefully.")
      return ret
    time.sleep(1 / freq)
  logging.warning("Killing the process.")
  p.kill()
  return p.wait()
111627
def run_later(self, callable_, timeout, *args, **kwargs):
        

        self.lock.acquire()
        try:
            if self.die:
                raise RuntimeError('This timer has been shut down and '
                                   'does not accept new jobs.')

            job = TimerTask(callable_, *args, **kwargs)
            self._jobs.append((job, time.time() + timeout))
            self._jobs.sort(key=lambda j: j[1])  # sort on time
            self.lock.notify()

            return job
        finally:
            self.lock.release()
1345563
function() {
        // Important to configure later to not use UTC.
        later.date.localTime();

        // Shutdown on schedule.
        if (this.get('shutdownSchedule')) {
            this._shutdownSchedule = later.parse.cron(this.get('shutdownSchedule'));
            if (this._shutdownInterval) {
                this._shutdownInterval.clear();
            }

            this._shutdownInterval = later.setInterval(_.bind(function() {
                logger.info('App shutdown time has arrived. ' + new Date());
                this.set('restartCount', 0);
                this.shutdownApp();
            }, this), this._shutdownSchedule);
        }

        // Shutdown on schedule.
        if (this.get('shutdownPcSchedule')) {
            this._shutdownPcSchedule = later.parse.cron(this.get('shutdownPcSchedule'));
            if (this._shutdownPcInterval) {
                this._shutdownPcInterval.clear();
            }

            this._shutdownPcInterval = later.setInterval(_.bind(function() {
                logger.info('Machine shutdown time has arrived. ' + new Date());
                this.set('restartCount', 0);
                this.shutdownMachine();
            }, this), this._shutdownPcSchedule);
        }

        // Start up on schedule.
        if (this.get('startupSchedule')) {
            this._startupSchedule = later.parse.cron(this.get('startupSchedule'));
            if (this._startupInterval) {
                this._startupInterval.clear();
            }

            this._startupInterval = later.setInterval(_.bind(function() {
                logger.info('App startup time has arrived. ' + new Date());
                if (!$$serverState.get('runApp')) {
                    logger.info('Startup disabled by console.');
                    return;
                }

                this.set('restartCount', 0);
                this.startApp();
            }, this), this._startupSchedule);
        }

        // Start up on schedule.
        if (this.get('restartSchedule')) {
            this._restartSchedule = later.parse.cron(this.get('restartSchedule'));
            if (this._restartInterval) {
                this._restartInterval.clear();
            }

            this._restartInterval = later.setInterval(_.bind(function() {
                if (this._isStartingUp || this._isShuttingDown) {
                    return;
                }

                logger.info('App restart time has arrived. ' + new Date());
                if (!$$serverState.get('runApp')) {
                    logger.info('Startup disabled by console.');
                    return;
                }

                this.set('restartCount', 0);
                this.restartApp();
            }, this), this._restartSchedule);
        }

        // Restart machine on schedule.
        if (this.get('restartPcSchedule')) {
            this._restartPcSchedule = later.parse.cron(this.get('restartPcSchedule'));
            if (this._restartPcInterval) {
                this._restartPcInterval.clear();
            }

            this._restartPcInterval = later.setInterval(_.bind(function() {
                logger.info('Machine restart time has arrived. ' + new Date());

                this.restartMachine();

            }, this), this._restartPcSchedule);
        }

    }
1213822
public void shutdown() {
    getLogger().info("removing receiverJob from the Scheduler.");

    if(this.repository instanceof LoggerRepositoryEx) {
      Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler();
      scheduler.delete(receiverJob);
    }
  }
405424
public function shutdownHandler()
    {
        $lastError = error_get_last();

        if (is_array($lastError)) {
            $this->errorHandler(
                $lastError[ 'type' ],
                $lastError[ 'message' ],
                $lastError[ 'file' ],
                $lastError[ 'line' ]
            );
        }
    }
576967
function shutdownAction(params) {
        logger.log('debug', 'M|shutdownAction|params=%j', params, meta);
        var forcefull = params.forcefull ? true : false;
        var action = forcefull ? 'stop' : 'shutdown';
        
        // 1) Make sure the Engine is in the RUNNING state before asking all the
        //    workers to disconnect.
        if (state !== states.running && state !== states.error) {
            logger.log('warn', 'M|shutdownAction|ERROR|REJECT');
            params.deferred.reject(new Error('Unable to ' + action + ' workers. Invalid state ' + states.toString(state) + '. Expected running or error'));
            return null;
        }
        
        // 2) Changing state to "Stopping" and use the monitorAllWorkerHelper function to 
        //    Queue all the workers, to monitor their shutting down progress.
        nextState(states.stopping);
        eachWorker(function(worker) {
            worker.send({
                "action"     : "stop",
                "id"         : worker.id,
                "origin"     : meta.module,
                "methodArgs" : [forcefull]
            });
        });
        var promises = monitorAllWorkerHelper(action, forcefull ? savedConfig.stopTimeoutInMs : savedConfig.shutdownTimeoutInMs);
        Q.all(promises).then(function (object) {
            logger.log('debug', 'M|%sAction|all|resolved|object=%j', action, object, meta);
            actionCompleted("shutdown", states.stopped, true, 'All workers shutdown', params);                        
        }).fail(function (object) {
            logger.log('debug', 'M|%sAction|all|rejected|object=%j', action, object, meta);
            actionCompleted("shutdown", states.error, false, 'Unable to stop workers', params);                        
        }).done();
        
        // 3) Ask nicely all the worker to stop accepting connection and exit.
        if (forcefull) {
            eachWorker(function (worker) {
                process.kill(worker.process.pid, 'SIGHUP');
            });
        } else {
            cluster.disconnect(function () {
                logger.log('debug', 'M|%s|disconnected|ALL-WORKERS-ARE-DEAD', action, meta);
            });
        }
        
        // 4) Return null, to inform the ActionQueue that this action should not
        //    be reinstered into the queue.
        return null;
    }
125294
def do_shutdown (self):
        """"""
        with self.mutex:
            unfinished = self.unfinished_tasks - len(self.queue)
            self.queue.clear()
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError('shutdown is in error')
                self.all_tasks_done.notifyAll()
            self.unfinished_tasks = unfinished
            self.shutdown = True
1140539
public function forceShutdown()
    {
        Event::fire(Event::WORKER_FORCE_SHUTDOWN, $this);

        if ($this->child === 0) {
            $this->log('Forcing shutdown of job <pop>'.$this->job.'</pop>', Logger::NOTICE);
        } else {
            $this->log('Forcing shutdown of worker <pop>'.$this.'</pop>', Logger::NOTICE);
        }

        $this->shutdown();
        $this->killChild();
    }
679218
@SneakyThrows
	public void gracefullyShutdown(Duration timeout) {
		logger.info("Shutting down...");

		if(!shuttingDown) {
			synchronized (this) {
				shuttingDown = true;
				threadPoolExecutor.shutdown();
			}

			// stops jobs that have not yet started to be executed
			for(Job job : jobStatus()) {
				Runnable runningJob = job.runningJob();
				if(runningJob != null) {
					threadPoolExecutor.remove(runningJob);
				}
				job.status(JobStatus.DONE);
			}
			synchronized (launcherNotifier) {
				launcherNotifier.set(false);
				launcherNotifier.notify();
			}
		}

		threadPoolExecutor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS);
	}
528348
def cleanShutdown(self, quickMode=False, stopReactor=True, _reactor=reactor):
        
        if self.shuttingDown:
            return
        log.msg("Initiating clean shutdown")
        self.shuttingDown = True
        # first, stop the distributor; this will finish any ongoing scheduling
        # operations before firing
        yield self.brd.disownServiceParent()

        # Double check that we're still supposed to be shutting down
        # The shutdown may have been cancelled!
        while self.shuttingDown:
            if quickMode:
                for builder in self.builders.values():
                    # As we stop the builds, builder.building might change during loop
                    # so we need to copy the list
                    for build in list(builder.building):
                        # if build is waited for then this is a sub-build, so
                        # no need to retry it
                        if sum(br.waitedFor for br in build.requests):
                            results = CANCELLED
                        else:
                            results = RETRY
                        is_building = build.workerforbuilder.state == States.BUILDING
                        build.stopBuild("Master Shutdown", results)
                        if not is_building:
                            # if it is not building, then it must be a latent worker
                            # which is substantiating. Cancel it.
                            build.workerforbuilder.worker.insubstantiate()
            # then wait for all builds to finish
            dl = []
            for builder in self.builders.values():
                for build in builder.building:
                    # build may be waiting for ping to worker to succeed which
                    # may never happen if the connection to worker was broken
                    # without TCP connection being severed
                    build.workerforbuilder.abortPingIfAny()

                    dl.append(build.waitUntilFinished())
            if not dl:
                log.msg("No running jobs, starting shutdown immediately")
            else:
                log.msg("Waiting for %i build(s) to finish" % len(dl))
                yield defer.DeferredList(dl)

            # Check that there really aren't any running builds
            n = 0
            for builder in self.builders.values():
                if builder.building:
                    num_builds = len(builder.building)
                    log.msg("Builder %s has %i builds running" %
                            (builder, num_builds))
                    n += num_builds
            if n > 0:
                log.msg(
                    "Not shutting down, there are %i builds running" % n)
                log.msg("Trying shutdown sequence again")
                yield util.asyncSleep(1)
            else:
                if stopReactor and self.shuttingDown:
                    log.msg("Stopping reactor")
                    _reactor.stop()
                break

        if not self.shuttingDown:
            yield self.brd.setServiceParent(self)
969802
def shutdown(self):
        """"""
        # cleanup
        self.started = False
        try:
            # nice way of doing things - let's wait until all items
            # in the queue are processed
            for t in self._threads:
                t.join()
        finally:
            # Emergency brake - if a KeyboardInterrupt is raised,
            # threads will finish processing current task and exit
            self.stopped = True