Trigger an asynchronous job to refresh the cache
977696
def async_refresh(self, *args, **kwargs):
        
        # We trigger the task with the class path to import as well as the
        # (a) args and kwargs for instantiating the class
        # (b) args and kwargs for calling the 'refresh' method

        try:
            enqueue_task(
                dict(
                    klass_str=self.class_path,
                    obj_args=self.get_init_args(),
                    obj_kwargs=self.get_init_kwargs(),
                    call_args=args,
                    call_kwargs=kwargs
                ),
                task_options=self.task_options
            )
        except Exception:
            # Handle exceptions from talking to RabbitMQ - eg connection
            # refused.  When this happens, we try to run the task
            # synchronously.
            logger.error("Unable to trigger task asynchronously - failing "
                         "over to synchronous refresh", exc_info=True)
            try:
                return self.refresh(*args, **kwargs)
            except Exception as e:
                # Something went wrong while running the task
                logger.error("Unable to refresh data synchronously: %s", e,
                             exc_info=True)
            else:
                logger.debug("Failover synchronous refresh completed successfully")
939457
def update_cache(self, data):
        """"""
        UTILS.update(self._cache, data)
        self._save_cache()
808353
function(result, cached, callback) {
            self.metacache.store(id, processor, cached, function(err) {
                if (err) return callback(err);
                callback(null, result);
            });
        }
899985
function reload() {
    var defer = q.defer();

    if (browserSync.active) {
        browserSync.reload();
        defer.resolve();
    } else
    startServer().then(defer.resolve);

    return defer.promise;
}
420547
function getCacheRefreshInterval() {
    var value = parseInt(process.env[CACHE_REFRESH_KEY]);

    // Should we 0 here to invalidate the cache immediately?
    if (value && !isNaN(value) && value > 0) {
      return value;
    }

    return DEFAULT_CACHE_REFRESH_SECONDS;
  }
942084
@SuppressWarnings("FutureReturnValueIgnored")
  void refreshIfNeeded(Node<K, V> node, long now) {
    if (!refreshAfterWrite()) {
      return;
    }
    K key;
    V oldValue;
    long oldWriteTime = node.getWriteTime();
    long refreshWriteTime = (now + ASYNC_EXPIRY);
    if (((now - oldWriteTime) > refreshAfterWriteNanos())
        && ((key = node.getKey()) != null) && ((oldValue = node.getValue()) != null)
        && node.casWriteTime(oldWriteTime, refreshWriteTime)) {
      try {
        CompletableFuture<V> refreshFuture;
        long startTime = statsTicker().read();
        if (isAsync) {
          @SuppressWarnings("unchecked")
          CompletableFuture<V> future = (CompletableFuture<V>) oldValue;
          if (Async.isReady(future)) {
            @SuppressWarnings("NullAway")
            CompletableFuture<V> refresh = future.thenCompose(value ->
              cacheLoader.asyncReload(key, value, executor));
            refreshFuture = refresh;
          } else {
            // no-op if load is pending
            node.casWriteTime(refreshWriteTime, oldWriteTime);
            return;
          }
        } else {
          @SuppressWarnings("NullAway")
          CompletableFuture<V> refresh = cacheLoader.asyncReload(key, oldValue, executor);
          refreshFuture = refresh;
        }
        refreshFuture.whenComplete((newValue, error) -> {
          long loadTime = statsTicker().read() - startTime;
          if (error != null) {
            logger.log(Level.WARNING, "Exception thrown during refresh", error);
            node.casWriteTime(refreshWriteTime, oldWriteTime);
            statsCounter().recordLoadFailure(loadTime);
            return;
          }

          @SuppressWarnings("unchecked")
          V value = (isAsync && (newValue != null)) ? (V) refreshFuture : newValue;

          boolean[] discard = new boolean[1];
          compute(key, (k, currentValue) -> {
            if (currentValue == null) {
              return value;
            } else if ((currentValue == oldValue) && (node.getWriteTime() == refreshWriteTime)) {
              return value;
            }
            discard[0] = true;
            return currentValue;
          }, /* recordMiss */ false, /* recordLoad */ false, /* recordLoadFailure */ true);

          if (discard[0] && hasRemovalListener()) {
            notifyRemoval(key, value, RemovalCause.REPLACED);
          }
          if (newValue == null) {
            statsCounter().recordLoadFailure(loadTime);
          } else {
            statsCounter().recordLoadSuccess(loadTime);
          }
        });
      } catch (Throwable t) {
        node.casWriteTime(refreshWriteTime, oldWriteTime);
        logger.log(Level.SEVERE, "Exception thrown when submitting refresh task", t);
      }
    }
  }
1115641
def post_save_update_cache(sender, instance, created, raw, **kwargs):
    """"""
    if raw:
        return
    name = sender.__name__
    if name in cached_model_names:
        delay_cache = getattr(instance, '_delay_cache', False)
        if not delay_cache:
            from .tasks import update_cache_for_instance
            update_cache_for_instance(name, instance.pk, instance)
863220
private void scheduleRenewalThresholdUpdateTask() {
        timer.schedule(new TimerTask() {
                           @Override
                           public void run() {
                               updateRenewalThreshold();
                           }
                       }, serverConfig.getRenewalThresholdUpdateIntervalMs(),
                serverConfig.getRenewalThresholdUpdateIntervalMs());
    }
559325
public function refresh()
    {
        $this->removeCache();
        $event = $this->eventManager->dispatch('refresh_cache', 'RefreshCache');
        $this->writeCache($event->getParameters());
    }
891985
function refresh() {
        $this->client = new $this->clientClassName($this->accessToken, $this->spaceId, $this->cacher);
        $this->requestDecorator = new RequestDecorator();
        $this->requestDecorator->setResource($this->resourceName);
    }
279626
private function _process() {

        // if caching is enabled but path doesn't exist, or is not writable
        if ($this->cache !== false && (!is_dir($this->cache['path']) || !is_writable($this->cache['path'])))

            // trigger an error and stop execution
            trigger_error('Cache path does not exists or is not writable', E_USER_ERROR);

        // iterate through the requests to process
        foreach ($this->_requests as $index => $request) {

            // if callback function is defined but it doesn't exists
            if ($request['callback'] != '' && !is_callable($request['callback']))

                // trigger an error and stop execution
                // the check is for when callback functions are defined as methods of a class
                trigger_error('Callback function "' . (is_array($request['callback']) ? array_pop($request['callback']) : $request['callback']) . '" does not exist', E_USER_ERROR);

            // if caching is enabled
            if ($this->cache !== false) {

                // get the name to be used for the cache file associated with the request
                $cache_file = $this->_get_cache_file_name($request);

                // if cache file exists and is not expired
                if (file_exists($cache_file) && filemtime($cache_file) + $this->cache['lifetime'] > time()) {

                    // if we have a callback
                    if ($request['callback'] != '') {

                        // prepare the arguments to pass to the callback function
                        $arguments = array_merge(

                            // made of the result from the cache file...
                            array(unserialize($this->cache['compress'] ? gzuncompress(file_get_contents($cache_file)) : file_get_contents($cache_file))),

                            // ...and any additional arguments (minus the first 2)
                            (array)$request['arguments']

                        );

                        // feed them as arguments to the callback function
                        call_user_func_array($request['callback'], $arguments);

                        // remove this request from the list so it doesn't get processed
                        unset($this->_requests[$index]);

                    }

                }

            }

        }

        // if there are any requests to process
        if (!empty($this->_requests)) {

            // initialize the multi handle
            // this will allow us to process multiple handles in parallel
            $this->_multi_handle = curl_multi_init();

            // queue the first batch of requests
            // (as many as defined by the "threads" property, or less if there aren't as many requests)
            $this->_queue_requests();

            // a flag telling the library if there are any requests currently processing
            $running = null;

            // loop
            do {

                // get status update
                while (($status = curl_multi_exec($this->_multi_handle, $running)) == CURLM_CALL_MULTI_PERFORM);

                // if no request has finished yet, keep looping
                if ($status != CURLM_OK) break;

                // if a request was just completed, we'll have to find out which one
                while ($info = curl_multi_info_read($this->_multi_handle)) {

                    // get handle of the completed request
                    $handle = $info['handle'];

                    // get content associated with the handle
                    $content = curl_multi_getcontent($handle);

                    // get the handle's ID
                    $resource_number = preg_replace('/Resource id #/', '', $handle);

                    // get the information associated with the request
                    $request = $this->_running['fh' . $resource_number];

                    // create a new object in which we will store all the data associated with the handle,
                    // as properties of this object
                    $result = new stdClass();

                    // get information about the request
                    $result->info = curl_getinfo($handle);

                    // extend the "info" property with the original URL
                    $result->info = array('original_url' => $request['url']) + $result->info;

                    // if request was a POST
                    if (isset($request['options'][CURLOPT_POSTFIELDS]) && $request['options'][CURLOPT_POSTFIELDS])

                        // put POST parameters in the response
                        $result->post = $request['options'][CURLOPT_POSTFIELDS];

                    // last request headers
                    $result->headers['last_request'] =

                        (

                            // if CURLINFO_HEADER_OUT is set
                            isset($request['options'][CURLINFO_HEADER_OUT]) &&

                            // if CURLINFO_HEADER_OUT is TRUE
                            $request['options'][CURLINFO_HEADER_OUT] == 1 &&

                            // if we actually have this information
                            isset($result->info['request_header'])

                        // extract request headers
                        ) ? $this->_parse_headers($result->info['request_header'], true) : '';

                    // remove request headers information from its previous location
                    unset($result->info['request_header']);

                    // get headers (unless we were explicitly told not to)
                    $result->headers['responses'] = (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1) ?

                        $this->_parse_headers(substr($content, 0, $result->info['header_size'])) :

                        '';

                    // get output (unless we were explicitly told not to)
                    $result->body = !isset($request['options'][CURLOPT_NOBODY]) || $request['options'][CURLOPT_NOBODY] == 0 ?

                        (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1 ?

                        substr($content, $result->info['header_size']) :

                        $content) :

                        '';

                    // if _htmlentities is set to TRUE, we're not doing a binary transfer and we have a body, run htmlentities() on it
                    if ($this->_htmlentities && !isset($request['options'][CURLOPT_BINARYTRANSFER]) && $result->body != '') {

                        // since PHP 5.3.0, htmlentities will return an empty string if the input string contains an
                        // invalid code unit sequence within the given encoding (utf-8 in our case)
                        // so take care of that
                        if (defined(ENT_IGNORE)) $result->body = htmlentities($result->body, ENT_IGNORE, 'utf-8');

                        // for PHP versions lower than 5.3.0
                        else htmlentities($result->body);

                    }

                    // get CURLs response code and associated message
                    $result->response = array($this->_response_messages[$info['result']], $info['result']);

                    // if we have a callback
                    if (isset($request['callback']) && $request['callback'] != '') {

                        // prepare the arguments to pass to the callback function
                        $arguments = array_merge(

                            // made of the "result" object...
                            array($result),

                            // ...and any additional arguments
                            $request['arguments']

                        );

                        // if downloaded a file
                        if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) {

                            // we make a dummy array with the first first 2 elements (which we also remove from the $arguments[0]->info array)
                            $tmp_array = array_splice($arguments[0]->info, 0, 2);

                            // make available the name we saved the file with
                            // (we need to merge the first 2 elements, our new array and the rest of the elements)
                            $arguments[0]->info = array_merge($tmp_array, array('downloaded_filename' => $this->_running['fh' . $resource_number]['file_name']), $arguments[0]->info);

                        }

                        // feed them as arguments to the callback function
                        // and save the callback's response, if any
                        $callback_response = call_user_func_array($request['callback'], $arguments);

                    // if no callback function, we assume the response is TRUE
                    } else $callback_response = true;

                    // if caching is enabled and the callback function did not return FALSE
                    if ($this->cache !== false && $callback_response !== false) {

                        // get the name of the cache file associated with the request
                        $cache_file = $this->_get_cache_file_name($request);

                        // cache the result
                        file_put_contents($cache_file, $this->cache['compress'] ? gzcompress(serialize($result)) : serialize($result));

                        // set rights on the file
                        chmod($cache_file, intval($this->cache['chmod'], 8));

                    }

                    // if there are more URLs to process and we're don't pause between batches of requests, queue the next one(s)
                    if (!empty($this->_requests) && !$this->pause_interval) $this->_queue_requests();

                    // remove the handle that we finished processing
                    // this needs to be done *after* we've already queued a new URL for processing
                    curl_multi_remove_handle($this->_multi_handle, $handle);

                    // make sure the handle gets closed
                    curl_close($handle);

                    // if we downloaded a file
                    if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER])

                        // close the associated file pointer
                        fclose($this->_running['fh' . $resource_number]['file_handler']);

                    // we don't need the information associated with this request anymore
                    unset($this->_running['fh' . $resource_number]);

                }

                // waits until curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM or until the timeout, whatever happens first
                // call usleep() if a select returns -1 - workaround for PHP bug: https://bugs.php.net/bug.php?id=61141
                if ($running && curl_multi_select($this->_multi_handle) === -1) usleep(100);

            // as long as there are threads running or requests waiting in the queue
            } while ($running || !empty($this->_running));

            // close the multi curl handle
            curl_multi_close($this->_multi_handle);

        }

    }
365603
def _refresh(self):
        
        log.debug('refreshing directory cache')
        self._users.update(list(self._user_gen()))
        self._channels.update(list(self._channel_gen()))
687321
def reload(force=false)
      raise ArgumentError, 'Argument must be true or false.' unless [true, false].include?(force)
      if force || reload?
        flush_cache
        return true
      end
      false
    end
347425
public function handleRefresh()
    {
        if ($this->hasPendingJob()) {
            return;
        }

        // Queue the job in the immediate queue
        $job = Injector::inst()->create(CheckForUpdatesJob::class);
        $jobDescriptorId = $this->getQueuedJobService()->queueJob($job, null, null, QueuedJob::IMMEDIATE);

        // Check the job descriptor on the queue
        $jobDescriptor = QueuedJobDescriptor::get()->filter('ID', $jobDescriptorId)->first();

        // If the job is not immediate, change it to immediate and reschedule it to occur immediately
        if ($jobDescriptor->JobType !== QueuedJob::IMMEDIATE) {
            $jobDescriptor->JobType = QueuedJob::IMMEDIATE;
            $jobDescriptor->StartAfter = null;
            $jobDescriptor->write();
        }
    }
1358900
public void refreshItems(List<CacheItem> itemsToRefresh, Cache cache) {
        for (CacheItem item : itemsToRefresh) {
            try {
                refreshItem(item, cache);
            } catch (Exception ex) {
                logger.error("Refresh for " + getScopeAndKeyString(item) + " failed", ex);
            }
        }
    }
1118499
def requeue_job(self, job, queue, priority, delayed_for=None):
        
        job.requeue(queue_name=queue._cached_name,
                    priority=priority,
                    delayed_for=delayed_for,
                    queue_model=self.queue_model)

        if hasattr(job, 'on_requeued'):
            job.on_requeued(queue)

        self.log(self.job_requeue_message(job, queue))
1360012
def refresh_from_server(self):
        """"""
        group = self.manager.get(id=self.id)
        self.__init__(self.manager, **group.data)