I want to run some shell commands like c:f , c:c etc by using cron.

3 Answers 3


Hi you can below code logic to run commands

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Process\PhpExecutableFinderFactory;
use Symfony\Component\Process\PhpExecutableFinder;
use Magento\Framework\Shell;
use Magento\Framework\Shell\CommandRenderer;
class CustomModel
    protected $_shell;

     * @var PhpExecutableFinder
    private $phpExecutableFinder;
    public function __construct(
        Shell $_shell,
        PhpExecutableFinderFactory $phpExecutableFinderFactory
    ) {
        $this->_shell = new Shell(new CommandRenderer());
        $this->phpExecutableFinder = $phpExecutableFinderFactory->create();

     * @param string $command
     * @throws LocalizedException
    public function run($command = 'cache:flush')
        $phpPath = $this->phpExecutableFinder->find() ?: 'php';

        $this->_shell->execute('%s %s %s', [$phpPath, BP . '/bin/magento', $command]);

just add this logic to your cron instance


Try this :-

public function __construct(
    \Magento\Framework\App\Cache\Manager $cacheManager
) {
    $this->cacheManager = $cacheManager;

private function whereYouNeedToCleanCache()

    // or this
  • thanks or your answer, but i want to run shell commands other then cache like custom indexers etc. Apr 29, 2022 at 9:19

Here is how I run a checkup for elasticsearch. it may be usefull to you, let me know :)

I'm using linux. nano /etc/crontab

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.


# m h dom mon dow user  command    

30 * * * * root php /var/www/html/teststore/app/code/elasticsearch.php

This script will run every 30 minutes.

Inside the php file I do the following instructions.Basically I check if the elasticsearch node is online and if not I kickstart it. Let me know if you need any further assistance


$ch = curl_init("http://localhost:9100");
$response = curl_exec($ch);

    shell_exec('sudo systemctl stop elasticsearch');
    shell_exec('sudo systemctl start elasticsearch');
    shell_exec('sudo systemctl enable elasticsearch');
    shell_exec('sudo php /var/www/html/teststore/bin/magento indexer:reindex');    



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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