Get the next run time/date for this Occurrence.
196502
public final GregorianCalendar getNextRunTime(GregorianCalendar schedule_start, int run_count)
    {
        Schedule schedule = getSchedule(run_count);
        return schedule == null ? null : schedule.getNextRunTime(schedule_start);
    }
482082
def get(self):
        
        now = datetime.now()
        if self._start_time:
            if self._stop_time:
                return (self._stop_time - self._start_time).total_seconds()
            return (now - self._start_time).total_seconds()
        return 0.
164133
def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE):
        '''
        
        '''
        if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None):
            warnings.warn(WARNING_CHANGE_MESSAGE, FutureWarning, 2)
            default_utc = False

        now = now or (datetime.utcnow() if default_utc and default_utc is not WARN_CHANGE else datetime.now())
        if isinstance(now, _number_types):
            now = datetime.utcfromtimestamp(now) if default_utc else datetime.fromtimestamp(now)

        # handle timezones if the datetime object has a timezone and get a
        # reasonable future/past start time
        onow, now = now, now.replace(tzinfo=None)
        tz = onow.tzinfo
        future = now.replace(microsecond=0) + increments[0]()
        if future < now:
            # we are going backwards...
            _test = lambda: future.year < self.matchers.year
            if now.microsecond:
                future = now.replace(microsecond=0)
        else:
            # we are going forwards
            _test = lambda: self.matchers.year < future.year

        # Start from the year and work our way down. Any time we increment a
        # higher-magnitude value, we reset all lower-magnitude values. This
        # gets us performance without sacrificing correctness. Still more
        # complicated than a brute-force approach, but also orders of
        # magnitude faster in basically all cases.
        to_test = ENTRIES - 1
        while to_test >= 0:
            if not self._test_match(to_test, future):
                inc = increments[to_test](future, self.matchers)
                future += inc
                for i in xrange(0, to_test):
                    future = increments[ENTRIES+i](future, inc)
                try:
                    if _test():
                        return None
                except:
                    print(future, type(future), type(inc))
                    raise
                to_test = ENTRIES-1
                continue
            to_test -= 1

        # verify the match
        match = [self._test_match(i, future) for i in xrange(ENTRIES)]
        _assert(all(match),
            "\nYou have discovered a bug with crontab, please notify the\n" \
            "author with the following information:\n" \
            "crontab: %r\n" \
            "now: %r", ' '.join(m.input for m in self.matchers), now)

        if not delta:
            onow = now = datetime(1970, 1, 1)

        delay = future - now
        if tz:
            delay += _fix_none(onow.utcoffset())
            if hasattr(tz, 'localize'):
                delay -= _fix_none(tz.localize(future).utcoffset())
            else:
                delay -= _fix_none(future.replace(tzinfo=tz).utcoffset())

        return delay.days * 86400 + delay.seconds + delay.microseconds / 1000000.
904466
def next(self):
        """"""
        # Check the state and find the next match as a side-effect if necessary.
        if not self.has_next():
            raise StopIteration("No next match")
        # Don't retain that memory any longer than necessary.
        result = self._last_match
        self._last_match = None
        self._state = PhoneNumberMatcher._NOT_READY
        return result
257019
@Override
	public Date getScheduleTime() {
		if (nextScheduleTimeAdd < 0) {
			return null;
		}
		
		long current = System.currentTimeMillis();
		
		Date nextSchedule = new Date(current + nextScheduleTimeAdd);
		logger.debug("Next schedule for job {} is set to {}", this.getClass().getSimpleName(), nextSchedule);
		
		return nextSchedule;
	}
908140
@Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        if (triggerContext.lastScheduledExecutionTime() == null) {
            return new Date(System.currentTimeMillis() + this.initialDelay);
        } else if (this.fixedRate) {
            return new Date(triggerContext.lastScheduledExecutionTime().getTime() + this.period);
        }
        return new Date(triggerContext.lastCompletionTime().getTime() + this.period);
    }
190445
def get_next(self):
        """"""
        return self.loop_time + (self.croniter.get_next(float) - self.time)
1074550
def get_next_occurrence(tx: ScheduledTransaction) -> date:
    
    # Reference documentation:
    # https://github.com/MisterY/gnucash-portfolio/issues/3

    # Preparing ref day is an important part before the calculation.
    # It should be:
    #   a) the last occurrence date + 1, or
    #   b) the recurrence start date - 1.
    # because the refDate is the date from which the due dates are being calculated. To include
    # the ones starting today, we need to calculate from the day before.
    ref_datum: Datum = Datum()
    if tx.last_occur:
        #ref_datum.set_value(tx.last_occur)
        ref_datum.from_date(tx.last_occur)
        ref_datum.add_days(1)
    else:
        ref_datum.from_date(tx.recurrence.recurrence_period_start)
        ref_datum.subtract_days(1)
    ref_date: datetime = ref_datum.value

    # today = datetimeutils.today_date()
    #today = Datum().today()
    # skipped schedule
    #if ref_date > today: 
    #    ref_date = today

    ###########################################################
    # The code below mimics the function
    # recurrenceNextInstance(const Recurrence *r, const GDate *refDate, GDate *nextDate)
    # https://github.com/Gnucash/gnucash/blob/115c0bf4a4afcae4269fe4b9d1e4a73ec7762ec6/libgnucash/engine/Recurrence.c#L172

    start_date: Datum = Datum()
    #start_date: datetime = tx.recurrence.recurrence_period_start
    start_date.from_date(tx.recurrence.recurrence_period_start)
    if ref_date < start_date.value:
        # If the occurrence hasn't even started, the next date is the start date.
        # this should also handle the "once" type in most cases.
        return start_date.value.date()

    # start at refDate.
    next_date: Datum = Datum()
    # next_date: datetime = ref_date
    next_date.from_datetime(ref_date)

    # last_date: datetime = tx.last_occur
    # print(tx.name, base_date, tx.recurrence.recurrence_period_start,
    #       tx.recurrence.recurrence_mult, tx.recurrence.recurrence_period_type)

    # /* Step 1: move FORWARD one period, passing exactly one occurrence. */

    mult: int = tx.recurrence.recurrence_mult
    period: str = tx.recurrence.recurrence_period_type
    wadj = tx.recurrence.recurrence_weekend_adjust

    # Not all periods from the original file are included at the moment.
    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        if period == RecurrencePeriod.YEAR.value:
            mult *= 12

        # handle weekend adjustment here.
        ## Takes care of short months.
        # next_weekday = datetimeutils.get_day_name(next_date)
        next_weekday = next_date.get_day_name()
        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and
                (next_weekday == "Saturday" or next_weekday == "Sunday")):
            # "Allows the following Friday-based calculations to proceed if 'next'
            #  is between Friday and the target day."
            days_to_subtract = 1 if next_weekday == "Saturday" else 2

            # next_date = datetimeutils.subtract_days(next_date, days_to_subtract)
            next_date.subtract_days(days_to_subtract)

        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and next_weekday == "Friday"):
            next_date = handle_friday(next_date, period, mult, start_date)

        # Line 274.
        temp_date = next_date.clone()
        if (temp_date.is_end_of_month() or
                (period in [RecurrencePeriod.MONTH.value, RecurrencePeriod.YEAR.value]
                 and (next_date.get_day() >= start_date.get_day()))
           ):
            # next_date = datetimeutils.add_months(next_date, mult)
            next_date.add_months(mult)
            # Set at end of month again (?!)
            #next_date = datetimeutils.get_end_of_month(next_date)
        else:
            # one fewer month fwd because of the occurrence in this month.
            next_date.add_months(mult - 1)

    # elif period == "once":
    #     next_date = tx.recurrence.recurrence_period_start

    elif period == RecurrencePeriod.DAY.value:
        logging.warning("daily not handled")

    else:
        logging.info(f"recurrence not handled: {period}")

    #######################
    # Step 2
    # "Back up to align to the base phase. To ensure forward
    # progress, we never subtract as much as we added (x % mult < mult)"

    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        n_months = (
            12 * (next_date.get_year() - start_date.get_year()) +
            (next_date.get_month() - start_date.get_month())
        )
        next_date.subtract_months(n_months % mult)

        # dim
        days_in_month = datetimeutils.get_days_in_month(
            next_date.get_year(), next_date.get_month())

        # Handle adjustment for 3 ways.
        if (period == RecurrencePeriod.END_OF_MONTH.value or
                next_date.get_day() >= days_in_month):
            # Set to last day of the month.
            next_date.set_day(days_in_month)
        else:
            # Same day as the start.
            next_date.set_day(start_date.get_day())

        # Adjust for dates on the weekend.
        if (period == RecurrencePeriod.YEAR.value or period == RecurrencePeriod.MONTH.value or
                period == RecurrencePeriod.END_OF_MONTH.value):
            weekday = next_date.get_day_name()
            if weekday == "Saturday" or weekday == "Sunday":
                if wadj == WeekendAdjustment.BACK.value:
                    next_date.subtract_days(1 if weekday == "Saturday" else 2)
                elif wadj == WeekendAdjustment.FORWARD.value:
                    next_date.add_days(2 if weekday == "Saturday" else 1)

    return next_date.value.date()
560910
def get_next_rngruns(self):
        
        available_runs = [result['params']['RngRun'] for result in
                          self.get_results()]
        yield from DatabaseManager.get_next_values(available_runs)
1119050
private void findNextExpireTime()
    {
        if (objects.size() == 0)
        {
            nextTimeSomeExpired = NO_OBJECTS;
        }
        else
        {
            nextTimeSomeExpired = NO_OBJECTS;
            Collection<Long> longs = null;
            synchronized (objects)
            {
                longs = new ArrayList(objectTimeStamps.values());
            }
            for (Iterator<Long> iterator = longs.iterator(); iterator.hasNext(); )
            {
                Long next = iterator.next() + timeToLive;
                if (nextTimeSomeExpired == NO_OBJECTS || next < nextTimeSomeExpired)
                {
                    nextTimeSomeExpired = next;
                }
            }
        }
    }
29353
def GetStartTime(self, problems=problems_module.default_problem_reporter):
    """"""
    cursor = self._schedule._connection.cursor()
    cursor.execute(
        'SELECT arrival_secs,departure_secs FROM stop_times WHERE '
        'trip_id=? ORDER BY stop_sequence LIMIT 1', (self.trip_id,))
    (arrival_secs, departure_secs) = cursor.fetchone()
    if arrival_secs != None:
      return arrival_secs
    elif departure_secs != None:
      return departure_secs
    else:
      problems.InvalidValue('departure_time', '',
                            'The first stop_time in trip %s is missing '
                            'times.' % self.trip_id)
405692
def scheduleNextHeartbeat(self, nextRun):
        
        import threading
        from datetime import datetime
        tilNextTime = max(nextRun - datetime.utcnow().timestamp(), 0)
        logging.getLogger('recorder').info("Scheduling next ping in " + str(round(tilNextTime, 3)) + " seconds")
        threading.Timer(tilNextTime, self.ping).start()
4281
private void estimateNextExecution() {
		synchronized (TIMER_LOCK) {
			if (fixedDelay) {
				scheduledExecutionTime = period + System.currentTimeMillis();
			} else {
				if (firstExecution == 0) {
					// save timestamp of first execution
					firstExecution = scheduledExecutionTime;
				}
				long now = System.currentTimeMillis();
				long executedTime = (numInvocations++ * period);
				scheduledExecutionTime = firstExecution + executedTime;
				if(logger.isDebugEnabled()) {
					logger.debug("next execution estimated to run at " + scheduledExecutionTime);
				}
				if(logger.isDebugEnabled()) {
					logger.debug("current time is " + now);
				}
			}
		}
	}
404648
def _find_next(server):
    
    from datetime import datetime
    #Re-load the database in case we have multiple instances of the script
    #running in memory.
    _load_db()
    result = None
    visited = []
    
    if "status" in db:
        for reponame, status in db["status"].items():
            vms("Checking cron status for {}: {}".format(reponame, status))
            start = None if "started" not in status else status["started"]
            end = None if "end" not in status else status["end"]
            running = start is not None and end is not None and start > end
            add = False
            
            if not running and end is not None:
                #Check the last time it was run and see if enough time has
                #elapsed.
                elapsed = (datetime.now() - end).seconds/60
                add = elapsed > server.cron.settings[reponame].frequency
                if not add:
                    vms("'{}' skipped because the interval hasn't ".format(reponame) +
                        "elapsed ({} vs. {})".format(elapsed, server.cron.settings[reponame].frequency))
            elif end is None:
                add = True

            if add:
                result = reponame
                break
            visited.append(reponame)
    else:
        db["status"] = {}        


    if result is None:
        #We still need to check the newly installed repos.            
        for reponame, repo in server.repositories.items():
            if reponame not in visited:
                #These are newly installed repos that have never run before.
                vms("Added '{}' as new repo for cron execution.".format(reponame))
                result = reponame
                break

    return result
265837
def get_next_occurrence(self) -> date:
        
        result = get_next_occurrence(self.transaction)
        assert isinstance(result, date)
        return result
1116507
def next(self):
        
        # Get next particle details
        x, y = self._move(self)
        colour = self._next_colour(self)
        char = self._next_char(self)
        self._last = char, x, y, colour[0], colour[1], colour[2]
        self.time += 1

        # Trigger any configured events
        if self.time == 1 and self._on_create is not None:
            self._on_create(self)
        elif self.life_time == self.time and self._on_destroy is not None:
            self._on_destroy(self)
        elif self._on_each is not None:
            self._on_each(self)

        return self._last
1270308
def x_runtime(f, *args, **kwargs):
    """"""

    _t0 = now()
    r = f(*args, **kwargs)
    _t1 = now()
    r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0)))

    return r