1

I need to setup cron job for indexing. Cron job run every day once.

1

If you're using Ubuntu you can open configured cron jobs by using command crontab -e

Let us assume that PHP is located in /user/bin and you installed Magento 2 in /var/www/html/magento2 directory.

Now let's say you want to run indexer every day once, you can configure it like this

5 0 * * * /usr/bin/php /var/www/html/magento2/bin/magento indexer:reindex

Here I assumed that you want to run the cron every day after 5 minutes midnight.

  • Thanks ! is that any coding part need to manage ? – shail Jul 4 '18 at 5:38
  • No, no coding required for cron setting. – Mohit Kumar Arora Jul 4 '18 at 6:17
1

You can create controller for reindexing and Add this controller in your cronjob :

.....

/**
 * @var \Magento\Indexer\Model\IndexerFactory
 */
protected $_indexerFactory;
/**
 * @var \Magento\Indexer\Model\Indexer\CollectionFactory
 */
protected $_indexerCollectionFactory;

public function __construct(
    \Magento\Indexer\Model\IndexerFactory $indexerFactory,
    \Magento\Indexer\Model\Indexer\CollectionFactory $indexerCollectionFactory
){
   $this->_indexerFactory = $indexerFactory;
   $this->_indexerCollectionFactory = $indexerCollectionFactory;
}

// Function for reindexing
public function reIndexing(){
   $indexerCollection = $this->_indexerCollectionFactory->create();
   $indexer_ids = $indexerCollection->getAllIds();
   foreach ($indexer_ids as $id) {
   $reindex_id = $this->_indexerFactory->create()->load($id);
   $reindex_id->reindexAll($id); // For reindexing all
   //$reindex_id->reindexRow($id); // For specific reindex.
}

.....

Or you can set it using crontab -e if you are using ubuntu.

0 22 * * * php /path/to/your/site/root/bin/magento index:reindex <index_type>

This cron will execute once in a day at 10 pm.

1

When you set main Magento 2 cron job, reindexing will be done automatically.

You can set main Magento 2 cron as follows.

#~ MAGENTO START
* * * * * /usr/bin/php /var/www/html/magento2/bin/magento cron:run 2>&1 | grep -v Ran jobs by schedule >> /var/www/html/magento2/var/log/magento.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/update/cron.php >> /var/www/html/magento2/var/log/update.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/bin/magento setup:cron:run >> /var/www/html/magento2/var/log/setup.cron.log
#~ MAGENTO END

Reference: https://devdocs.magento.com/guides/v2.2/config-guide/cli/config-cli-subcommands-cron.html

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.