u"""
        Clean up expired records.

        Will remove all entries for any ChordData whose callback result is in
        state <status> that was marked completed more than
        (self.expires * <expires_multipler>) ago.
325325
def _cleanup(self, status, expires_multiplier=1):
        
        """
        # self.expires is inherited, and defaults to 1 day (or setting CELERY_TASK_RESULT_EXPIRES)
        expires = self.expires if isinstance(self.expires, timedelta) else timedelta(seconds=self.expires)
        expires = expires * expires_multiplier
        chords_to_delete = ChordData.objects.filter(
            callback_result__date_done__lte=datetime.now() - expires,
            callback_result__status=status
        ).iterator()
        for _chord in chords_to_delete:
            subtask_ids = [subtask.task_id for subtask in _chord.completed_results.all()]
            _chord.completed_results.clear()
            TaskMeta.objects.filter(task_id__in=subtask_ids).delete()
            _chord.callback_result.delete()
            _chord.delete()
988710
private void expireAndRemoveEventually(final Entry e) {
    if (isKeepAfterExpired() || e.isProcessing()) {
      metrics.expiredKept();
    } else {

      removeEntry(e);
    }
  }
455042
public void endRecord_() {
    // this is where we actually update the link database. basically,
    // all we need to do is to retract those links which weren't seen
    // this time around, and that can be done via assertLink, since it
    // can override existing links.

    // get all the existing links
    Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current));

    // build a hashmap so we can look up corresponding old links from
    // new links
    if (oldlinks != null) {
      Map<String, Link> oldmap = new HashMap(oldlinks.size());
      for (Link l : oldlinks)
        oldmap.put(makeKey(l), l);

      // removing all the links we found this time around from the set of
      // old links. any links remaining after this will be stale, and need
      // to be retracted
      for (Link newl : new ArrayList<Link>(curlinks)) {
        String key = makeKey(newl);
        Link oldl = oldmap.get(key);
        if (oldl == null)
          continue;

        if (oldl.overrides(newl))
          // previous information overrides this link, so ignore
          curlinks.remove(newl);
        else if (sameAs(oldl, newl)) {
          // there's no new information here, so just ignore this
          curlinks.remove(newl);
          oldmap.remove(key); // we don't want to retract the old one
        } else
          // the link is out of date, but will be overwritten, so remove
          oldmap.remove(key);
      }

      // all the inferred links left in oldmap are now old links we
      // didn't find on this pass. there is no longer any evidence
      // supporting them, and so we can retract them.
      for (Link oldl : oldmap.values())
        if (oldl.getStatus() == LinkStatus.INFERRED) {
          oldl.retract(); // changes to retracted, updates timestamp
          curlinks.add(oldl);
        }
    }

    // okay, now we write it all to the database
    for (Link l : curlinks)
      linkdb.assertLink(l);
  }
964553
def sweep(self):
        '''
        
        '''
        if self.max_age < time.time() - self.timestamp:
            self.clear()
            self.timestamp = time.time()
        else:
            paterns = list(self.cache.values())
            paterns.sort()
            for idx in range(self.clear_size):
                del self.cache[paterns[idx][2]]
1125469
public function clearExpired()
    {
        if (! $this->enabled) {
            return;
        }
        $error = false;

        set_error_handler(function () use (&$error) {
            $error = true;
        }, E_WARNING);
        foreach (glob($this->getPath() . '/*.dat') as $file) {
            if (filemtime($file) < time()) {
                unlink($file);
            }
        }
        restore_error_handler();

        return ! $error;
    }
125350
def delete_expired(self, expires):
        """"""
        meta = self.model._meta
        with commit_on_success():
            self.get_all_expired(expires).update(hidden=True)
            cursor = self.connection_for_write().cursor()
            cursor.execute(
                'DELETE FROM {0.db_table} WHERE hidden=%s'.format(meta),
                (True, ),
            )
617244
private void cleanupStaleClients() {
    LocalTime cleanupTime = LocalTime.now();
    LOG.debug("Starting cleanup authentication registry at {}", cleanupTime);
    // Get a list of stale clients under read lock.
    List<UUID> staleChannels = new ArrayList<>();
    for (Map.Entry<UUID, AuthenticatedChannelInfo> clientEntry : mChannels.entrySet()) {
      LocalTime lat = clientEntry.getValue().getLastAccessTime();
      if (lat.plusSeconds(mCleanupIntervalMs / 1000).isBefore(cleanupTime)) {
        staleChannels.add(clientEntry.getKey());
      }
    }

    // Unregister stale clients.
    LOG.debug("Found {} stale channels for cleanup.", staleChannels.size());
    for (UUID clientId : staleChannels) {
      unregisterChannel(clientId);
    }
    LOG.debug("Finished state channel cleanup at {}", LocalTime.now());
  }
79837
def clean_expired_user_attempts(attempt_time: datetime = None) -> int:
    

    if settings.AXES_COOLOFF_TIME is None:
        log.debug('AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured')
        return 0

    threshold = get_cool_off_threshold(attempt_time)
    count, _ = AccessAttempt.objects.filter(attempt_time__lt=threshold).delete()
    log.info('AXES: Cleaned up %s expired access attempts from database that were older than %s', count, threshold)
    return count
869009
private void cleanupLists(PrefixKey key) {
    // Remove expired list entries. Keep track of the last list removed.
    NavigableMap<PrefixKey, CacheValue<Object>> head = prefixMap.headMap(key, true).descendingMap();
    Iterator<Entry<PrefixKey, CacheValue<Object>>> headItr = head.entrySet().iterator();
    Entry<PrefixKey, CacheValue<Object>> last = null;

    while (headItr.hasNext()) {
      Entry<PrefixKey, CacheValue<Object>> entry = headItr.next();
      if (isExpired(entry.getValue()) && key.isParent(entry.getKey())) {
        last = entry;
        headItr.remove();
      }
    }

    // If a list was removed, check its contained items for expiration.
    if (last != null) {
      SortedMap<PrefixKey, CacheValue<GoogleCloudStorageItemInfo>> prefix =
          getPrefixSubMap(itemMap, last.getKey());
      prefix.entrySet().removeIf(entry -> isExpired(entry.getValue()));
    }
  }
819762
def _device_expiry_callback(self):
        """"""

        expired = 0
        for adapters in self._devices.values():
            to_remove = []
            now = monotonic()

            for adapter_id, dev in adapters.items():
                if 'expires' not in dev:
                    continue

                if now > dev['expires']:
                    to_remove.append(adapter_id)
                    local_conn = "adapter/%d/%s" % (adapter_id, dev['connection_string'])

                    if local_conn in self._conn_strings:
                        del self._conn_strings[local_conn]

            for entry in to_remove:
                del adapters[entry]
                expired += 1

        if expired > 0:
            self._logger.info('Expired %d devices', expired)
1112766
public void checkKeepOrRemove() {
    boolean _hasKeepAfterExpired = heapCache.isKeepAfterExpired();
    if (expiry != 0 || remove || _hasKeepAfterExpired) {
      mutationUpdateHeap();
      return;
    }
    if (_hasKeepAfterExpired) {
      expiredImmediatelyKeepData();
      return;
    }
    expiredImmediatelyAndRemove();
  }
1284529
function validateExpires(req, expires) {
	if(!expires) {
		return false;
	}
	if(Date.now() - (expires * 1000) > 0) {
		clearAllPersistentData(req);
		return false;
	}
	return true;
}
143989
private void sweepExpiredNonces() {

        // Do not sweep until enough time has elapsed since the last sweep
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastSweep < SWEEP_INTERVAL)
            return;

        // Record time of sweep
        lastSweep = currentTime;

        // For each stored nonce
        Iterator<Map.Entry<String, Long>> entries = nonces.entrySet().iterator();
        while (entries.hasNext()) {

            // Remove all entries which have expired
            Map.Entry<String, Long> current = entries.next();
            if (current.getValue() <= System.currentTimeMillis())
                entries.remove();

        }

    }
804454
protected static function clear_old_records() {
        global $DB;

        $sql = "SELECT dpctx.*
                  FROM {tool_dataprivacy_ctxexpired} dpctx
             LEFT JOIN {context} ctx ON ctx.id = dpctx.contextid
                 WHERE ctx.id IS NULL";

        $orphaned = $DB->get_recordset_sql($sql);
        foreach ($orphaned as $orphan) {
            $expiredcontext = new expired_context(0, $orphan);
            $expiredcontext->delete();
        }

        // Delete any child of a user context.
        $parentpath = $DB->sql_concat('ctxuser.path', "'/%'");
        $params = [
            'contextuser' => CONTEXT_USER,
        ];

        $sql = "SELECT dpctx.*
                  FROM {tool_dataprivacy_ctxexpired} dpctx
                 WHERE dpctx.contextid IN (
                    SELECT ctx.id
                        FROM {context} ctxuser
                        JOIN {context} ctx ON ctx.path LIKE {$parentpath}
                       WHERE ctxuser.contextlevel = :contextuser
                    )";
        $userchildren = $DB->get_recordset_sql($sql, $params);
        foreach ($userchildren as $child) {
            $expiredcontext = new expired_context(0, $child);
            $expiredcontext->delete();
        }
    }
51113
def purge_old(self):
        '''
        
        '''
        if self.keep_max is not None:
            keys = self.redis_conn.keys(self.get_key() + ':*')
            keys.sort(reverse=True)
            while len(keys) > self.keep_max:
                key = keys.pop()
                self.redis_conn.delete(key)
663756
@Scheduled(initialDelayString = "${cas.authn.mfa.trusted.cleaner.schedule.startDelay:PT10S}",
        fixedDelayString = "${cas.authn.mfa.trusted.cleaner.schedule.repeatInterval:PT60S}")
    public void clean() {

        if (!trustedProperties.getCleaner().getSchedule().isEnabled()) {
            LOGGER.debug("[{}] is disabled. Expired trusted authentication records will not automatically be cleaned up by CAS", getClass().getName());
            return;
        }

        try {
            LOGGER.debug("Proceeding to clean up expired trusted authentication records...");
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            val validDate = LocalDateTime.now().minus(trustedProperties.getExpiration(),
                DateTimeUtils.toChronoUnit(trustedProperties.getTimeUnit()));
            LOGGER.info("Expiring records that are on/before [{}]", validDate);
            this.storage.expire(validDate);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
266507
private void pruneExcessiveHistoricalRecordsLocked() {
        List<HistoricalRecord> choiceRecords = mHistoricalRecords;
        final int pruneCount = choiceRecords.size() - mHistoryMaxSize;
        if (pruneCount <= 0) {
            return;
        }
        mHistoricalRecordsChanged = true;
        for (int i = 0; i < pruneCount; i++) {
            HistoricalRecord prunedRecord = choiceRecords.remove(0);
            if (DEBUG) {
                Log.i(LOG_TAG, "Pruned: " + prunedRecord);
            }
        }
    }