DetermineSleepTime(struct timeval *timeout)
{
	TimestampTz next_wakeup = 0;

	/*
	 * Normal case: either there are no background workers at all, or we're in
	 * a shutdown sequence (during which we ignore bgworkers altogether).
	 */
	if (Shutdown > NoShutdown ||
		(!StartWorkerNeeded && !HaveCrashedWorker))
	{
		if (AbortStartTime != 0)
		{
			/* time left to abort; clamp to 0 in case it already expired */
			timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
				(time(NULL) - AbortStartTime);
			timeout->tv_sec = Max(timeout->tv_sec, 0);
			timeout->tv_usec = 0;
		}
		else
		{
			timeout->tv_sec = 60;
			timeout->tv_usec = 0;
		}
		return;
	}

	if (StartWorkerNeeded)
	{
		timeout->tv_sec = 0;
		timeout->tv_usec = 0;
		return;
	}

	if (HaveCrashedWorker)
	{
		slist_mutable_iter siter;

		/*
		 * When there are crashed bgworkers, we sleep just long enough that
		 * they are restarted when they request to be.  Scan the list to
		 * determine the minimum of all wakeup times according to most recent
		 * crash time and requested restart interval.
		 */
		slist_foreach_modify(siter, &BackgroundWorkerList)
		{
			RegisteredBgWorker *rw;
			TimestampTz this_wakeup;

			rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);

			if (rw->rw_crashed_at == 0)
				continue;

			if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
				|| rw->rw_terminate)
			{
				ForgetBackgroundWorker(&siter);
				continue;
			}

			this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
													  1000L * rw->rw_worker.bgw_restart_time);
			if (next_wakeup == 0 || this_wakeup < next_wakeup)
				next_wakeup = this_wakeup;
		}
	}

	if (next_wakeup != 0)
	{
		long		secs;
		int			microsecs;

		TimestampDifference(GetCurrentTimestamp(), next_wakeup,
							&secs, &microsecs);
		timeout->tv_sec = secs;
		timeout->tv_usec = microsecs;

		/* Ensure we don't exceed one minute */
		if (timeout->tv_sec > 60)
		{
			timeout->tv_sec = 60;
			timeout->tv_usec = 0;
		}
	}
	else
	{
		timeout->tv_sec = 60;
		timeout->tv_usec = 0;
	}
}
Unknown