Skip to main content
Category:

in this tuto, I'll show you how to run cron programmatically in Drupal 8.

Drupal core has an Interface for running cron tasks Drupal\Core\CronInterface.

To Execute a cron run, juste apply Drupal\Core\CronInterface::run() method.

<?php

namespace Drupal\mymodule\Controller;

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

/**
 * Class MyModuleController
 * @package Drupal\mymodule\Controller
 */
class MyModuleController extends ControllerBase
{
  /**
   * @var CronInterface
   */
  protected $cron;

  /**
   * MyModuleController constructor.
   * @param CronInterface $cron
   */
  public function __construct(CronInterface $cron){
    $this->cron = $cron;
  }

  /**
   * @param ContainerInterface $container
   * @return ControllerBase|MyModuleController
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cron')
    );
  }

  /**
   * @return array
   */
  public function index()
  {
    $this->cron->run();
    $this->messenger()->addMessage($this->t('Cron ran successfully.'));
    return array(
      '#type' => 'markup',
      '#markup' => "Cron ran successfully."
    );
  }

}

 

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook