Deletes chunk files older then 1 hour, in case there are some left.
347237
protected function cleanupOldChunks()
    {
        if ($this->useChunks === false) {
            // We have no write access. Do nothing.
            return;
        }

        static $beenHere = false;

        // We only do this once.
        if ($beenHere === true) {
            return;
        }

        $beenHere = true;
        // Clean up leftover files.
        $chunkList = glob($this->chunkDir . '*.Krexx.tmp');
        if (empty($chunkList) === false) {
            $now = time();
            foreach ($chunkList as $file) {
                // We delete everything that is older than 15 minutes.
                if (($this->pool->fileService->filetime($file) + 900) < $now) {
                    $this->pool->fileService->deleteFile($file);
                }
            }
        }
    }
271799
void deleteNewAndOldFiles() {

        fa.removeElement(fileName + ".data" + ".old");
        fa.removeElement(fileName + ".data" + ".new");
        fa.removeElement(fileName + ".backup" + ".new");
        fa.removeElement(scriptFileName + ".new");
    }
128090
private void purgeUploadedFiles() {
        long currentTimeMillis = System.currentTimeMillis();

        // Do purge if purge delay is past before last purge
        // -------------------------------------------------
        long nextPurgeInMillis =
                this.m_lastPurgeInMillis + this.m_purgeDelayInMillis;
        if (nextPurgeInMillis < currentTimeMillis) {
            this.m_lastPurgeInMillis = currentTimeMillis;

            // Compute limit file time to purged
            // ---------------------------------
            long minStartTime =
                    currentTimeMillis - (this.m_uploadStorageMinutes * 60000);

            // List files to purge and remove filename to map
            // This operation is synchronized to be thread-safe
            // ------------------------------------------------
            final List<String> removeList = new ArrayList<String>();
            synchronized (this.m_uploadStartTime) {
                for (Entry<String, Long> entry :
                        m_uploadStartTime.entrySet()) {
                    String filename = entry.getKey();
                    long startTime = entry.getValue().longValue();
                    if (startTime < minStartTime) {
                        removeList.add(filename);
                    }
                }
                for (String filename : removeList) {
                    this.m_uploadStartTime.remove(filename);
                }
            }

            // Delete file to purged
            // This operation is out of synchronised block for performances
            // ------------------------------------------------------------
            for (int i = 0; i < removeList.size(); i++) {
                String id = removeList.get(i);

                File file = new File(this.m_tempDir, id);
                if (file.exists()) {
                    if (file.delete()) {
                        logger.info("Removed uploaded file '{}' because it expired.", id);
                    } else {
                        logger.warn("Could not remove expired uploaded file '"
                                    + id + "'. Check permissions in " + m_tempDir.getPath() + " directory.");
                    }
                }
            }
        }
    }
321667
private static void deleteOldAndEmptyFiles() {
            File dir = LOG_FILE_DIR;
            if (dir.exists()) {
                File[] files = dir.listFiles();

                for (File f : files) {
                    if (f.length() == 0 ||
                            f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {
                        f.delete();
                    }
                }
            }
        }
284995
def _clean(self):
        """"""
        if self._workers:
            for url in self._workers.copy():
                w = self._workers[url]
                if w.is_finished():
                    self._workers.pop(url)
                    self._paths.pop(url)
                    if url in self._get_requests:
                        self._get_requests.pop(url)

        else:
            self._timer.stop()
544099
private function removeOldFiles()
    {
        if ($handle = opendir($this->uploadDir)) {

            while (false !== ($file = readdir($handle))) {
                if (is_file($file)) {
                    if (filectime($this->uploadDir . $file) < (time() - $this->fileHandleTime)) {
                        unlink($this->uploadDir . $file);
                    }
                }
            }
        }
    }
119541
def cleanup(self, timeout):
        '''
        
        '''
        cutoff = time() - timeout
        self.collection.remove({_atime: {'$lt': cutoff}})
331005
def clean_old_jobs():
    '''
    
    '''
    if __opts__['keep_jobs'] != 0:
        jid_root = _job_dir()

        if not os.path.exists(jid_root):
            return

        # Keep track of any empty t_path dirs that need to be removed later
        dirs_to_remove = set()

        for top in os.listdir(jid_root):
            t_path = os.path.join(jid_root, top)

            if not os.path.exists(t_path):
                continue

            # Check if there are any stray/empty JID t_path dirs
            t_path_dirs = os.listdir(t_path)
            if not t_path_dirs and t_path not in dirs_to_remove:
                dirs_to_remove.add(t_path)
                continue

            for final in t_path_dirs:
                f_path = os.path.join(t_path, final)
                jid_file = os.path.join(f_path, 'jid')
                if not os.path.isfile(jid_file) and os.path.exists(f_path):
                    # No jid file means corrupted cache entry, scrub it
                    # by removing the entire f_path directory
                    shutil.rmtree(f_path)
                elif os.path.isfile(jid_file):
                    jid_ctime = os.stat(jid_file).st_ctime
                    hours_difference = (time.time() - jid_ctime) / 3600.0
                    if hours_difference > __opts__['keep_jobs'] and os.path.exists(t_path):
                        # Remove the entire f_path from the original JID dir
                        try:
                            shutil.rmtree(f_path)
                        except OSError as err:
                            log.error('Unable to remove %s: %s', f_path, err)

        # Remove empty JID dirs from job cache, if they're old enough.
        # JID dirs may be empty either from a previous cache-clean with the bug
        # Listed in #29286 still present, or the JID dir was only recently made
        # And the jid file hasn't been created yet.
        if dirs_to_remove:
            for t_path in dirs_to_remove:
                # Checking the time again prevents a possible race condition where
                # t_path JID dirs were created, but not yet populated by a jid file.
                t_path_ctime = os.stat(t_path).st_ctime
                hours_difference = (time.time() - t_path_ctime) / 3600.0
                if hours_difference > __opts__['keep_jobs']:
                    shutil.rmtree(t_path)
255555
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)):
        """"""
        q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS')
        '''
        log.info('Cleaning up full_hash entries expired more than {} seconds ago.'.format(keep_expired_for))
        with self.get_cursor() as dbc:
            dbc.execute(q.format(int(keep_expired_for)))
98885
def remove_expired_multipartobjects():
    """"""
    delta = current_app.config['FILES_REST_MULTIPART_EXPIRES']
    expired_dt = datetime.utcnow() - delta

    file_ids = []
    for mp in MultipartObject.query_expired(expired_dt):
        file_ids.append(str(mp.file_id))
        mp.delete()

    for fid in file_ids:
        remove_file_data.delay(fid)
902801
def clear_old_log_entries():
    
    if hasattr(settings, 'DJANGO_CRON_DELETE_LOGS_OLDER_THAN'):
        delta = timedelta(days=settings.DJANGO_CRON_DELETE_LOGS_OLDER_THAN)
        CronJobLog.objects.filter(end_time__lt=get_current_time() - delta).delete()
1002626
protected void cleanupSfDumps(boolean deleteOldest)
  {
    // Check what the maximum number of dumpfiles and the max allowable
    // aggregate dump file size is.
    int maxDumpFiles =
        System.getProperty(MAX_NUM_DUMP_FILES_PROP) != null ?
        Integer.valueOf(System.getProperty(MAX_NUM_DUMP_FILES_PROP)) :
        DEFAULT_MAX_DUMP_FILES;

    int maxDumpDirSizeMB =
        System.getProperty(MAX_SIZE_DUMPS_MB_PROP) != null ?
        Integer.valueOf(System.getProperty(MAX_SIZE_DUMPS_MB_PROP)) :
        DEFAULT_MAX_DUMPDIR_SIZE_MB;

    File dumpDir = new File(logDumpPathPrefix);
    long dirSizeBytes = 0;

    if (dumpDir.listFiles() == null)
    {
      return;
    }

    // Keep a sorted list of files by size as we go in case we need to
    // delete some
    TreeSet<File> fileList =
        new TreeSet<>(new Comparator<File>()
        {
          @Override
          public int compare(File a, File b)
          {
            return a.length() < b.length() ? -1 : 1;
          }
        });

    // Loop over files in this directory and get rid of old ones
    // while accumulating the total size
    for (File file : dumpDir.listFiles())
    {
      if ((!file.getName().startsWith(LOG_DUMP_FILE_NAME) &&
           !file.getName().startsWith(IncidentUtil.INC_DUMP_FILE_NAME)) ||
          (System.currentTimeMillis() - file.lastModified() > FILE_EXPN_TIME_MS &&
           file.delete()))
      {
        continue;
      }

      dirSizeBytes += file.length();
      fileList.add(file);
    }

    // If we're exceeding our max allotted disk usage, cut some stuff out;
    // else if we need to make space for a new dump delete the oldest.
    if (dirSizeBytes >= ((long) maxDumpDirSizeMB << 20))
    {
      // While we take up more than half the allotted disk usage, keep deleting.
      for (File file : fileList)
      {
        if (dirSizeBytes < ((long) maxDumpDirSizeMB << 19))
        {
          break;
        }

        long victimSize = file.length();
        if (file.delete())
        {
          dirSizeBytes -= victimSize;
        }
      }
    }
    else if (deleteOldest && fileList.size() >= maxDumpFiles)
    {
      fileList.first().delete();
    }
  }
348418
public void clean() {
        Instant minAge = Instant.now().minus(storageTimeInSeconds, ChronoUnit.SECONDS);
        synchronized (messages) {
            messages.removeIf(messageRef -> Optional.ofNullable(messageRef.get())
                    .map(message -> !message.isCachedForever() && message.getCreationTimestamp().isBefore(minAge))
                    .orElse(true));
            long foreverCachedAmount = messages.stream()
                    .map(Reference::get)
                    .filter(Objects::nonNull)
                    .filter(Message::isCachedForever)
                    .count();
            messages.removeAll(messages.stream()
                                       .filter(messageRef -> Optional.ofNullable(messageRef.get())
                                               .map(message -> !message.isCachedForever())
                                               .orElse(true))
                                       .limit(Math.max(0, messages.size() - capacity - foreverCachedAmount))
                                       .collect(Collectors.toList()));
        }
    }
889396
public function clear()
    {
        $now = Carbon::now('UTC');

        ORM::for_table('files_downloads')
            ->where_lt('created_at', $now->subHours(SettingsFile::TOKENS_OLDER_THAN_HOURS))
            ->delete_many();
    }
353324
public function delete() {
        if ($this->_oldFile != $this->path . $this->name) {
            unlink($this->_oldFile);
        }

        unlink($this->path . $this->name);
    }
50977
static function cleanup()
    {
        $ini = eZINI::instance();
        $db = eZDB::instance();
        $timeFrame = 1;
        if ( $ini->hasVariable( 'TipAFriend', 'TimeFrame' ) )
            $timeFrame = $ini->variable( 'TipAFriend', 'TimeFrame' );
        $time = time() - $timeFrame * 3600;

        $db->query( "DELETE FROM eztipafriend_request
                      WHERE created < $time " );
    }
314068
def clean_old_jobs():
    '''
    
    '''
    if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
        try:
            with _get_serv() as cur:
                sql = 'select date_sub(now(), interval {0} hour) as stamp;'.format(__opts__['keep_jobs'])
                cur.execute(sql)
                rows = cur.fetchall()
                stamp = rows[0][0]

            if __opts__.get('archive_jobs', False):
                _archive_jobs(stamp)
            else:
                _purge_jobs(stamp)
        except MySQLdb.Error as e:
            log.error('Mysql returner was unable to get timestamp for purge/archive of jobs')
            log.error(six.text_type(e))
            raise salt.exceptions.SaltRunnerError(six.text_type(e))