I'm using the Deploy suite, which requires cron to be run after a deployment is created. However, when I try to execute \Drupal\Core\Cron::run(); from hook_entity_create() or from a route Class, it doesn't work. It dies after hitting $this->accountSwitcher->switchTo(new AnonymousUserSession());, throwing the error Using $this when not in object context in Drupal\Core\Cron::run().

Is this just simply not possible? Is there a way around these errors?


The reason why you get that error is because run is not expected to be called statically. \Drupal\Core\Cron is a service class managed by Drupal, registered in core.services.yml. To get a reference to the instance of this service, you'll need to inject the dependency to your controller.

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\CronInterface;

class MyController extends ControllerBase {

  protected $cron;

  public function __construct(CronInterface $cron) {
    $this->cron = $cron;

  public static function create(ContainerInterface $container) {
    return new static(

  public function myPage() {

To call it from a hook, if you'll need to use \Drupal::service() to get a reference to the instance:

$cron = \Drupal::service('cron');

A full example of how to manually run cron can be found in the implementation of the Cron settings page (Configure -> System -> Cron). In that page, you have a button to manually run the cron. See the runCron method, which is attached as the submit handler of the "Run cron" button.

| improve this answer | |
  • Thank you, incredibly helpful. Forgot that services existed! – Mrweiner Oct 3 '19 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.