How to Refresh Cache using Cron in Magento?

In Magento, most of the times you make changes to products, static blocks, etc but its will shows the changes on frontend then you will need to go into System > Cache Management > Refresh the invalidated cache types but I’ve overcome this by using a Cron job that runs every time Cron runs on the server and calls a function to refresh the cache automatically.
If you want to refresh all cache at specified intervals, like once a day at midnight so you will check below steps.

Method 1:

Below script Is used to automatically refresh cache In Magento. This Script doesn’t refresh all the cache every time it will run, but it will refresh only an invalid cache which is required to refresh.

Create a file: Refreshcroncache.php

<?php
ini_set('max_execution_time', 18000);
require_once 'app/Mage.php';
$app = Mage::app('admin');
umask(0);
Mage::setIsDeveloperMode(true);
//Cache Refresh Start

$invalidatedTypes = Mage::app()->getCacheInstance()->getInvalidatedTypes();
foreach ($invalidatedTypes as $type) {
    Mage::app()->getCacheInstance()->cleanType($type->getId());
    Mage::log('Cache Type '.$type->getId()." Is Refresh.",null,'Refresh_Cache.log');
}
//Cache Refresh End
?>

Set Cron For Refreshcroncache.php File via SSH Enter Following Command

/15 10 * * * sh /path/to/your/Refreshcroncache.php

Method 2 :

Create a module (or use an existing module) that you can use to set up a Cron job for refreshing the cache.Create a file: {{namespace}}/{{modulename}}/Model/Observer.php

Inside that file:

<?php

  class <namespace>_<modulename>_Model_Observer {

    public function refreshbycronCache() {
      try {
        $allTypes = Mage::app()->useCache();
        foreach($allTypes as $type => $blah) {
          Mage::app()->getCacheInstance()->cleanType($type);
        }
      } catch (Exception $e) {
        // do something
        error_log($e->getMessage());
      }
    }

  }

In your module’s etc/config.xml:

<config>
    ...
    <crontab>
      <jobs>
        <{{modulename}}_refresh_cache>
          <schedule><cron_expr>* * * * *</cron_expr></schedule>
          <run><model>{{modulename}}/observer::refreshbycronCache</model></run>
        </{{modulename}}_refresh_cache>
      </jobs>
    </crontab>
    ...
  </config>

Now as long as cron is configured correctly on your server, the cache will update automatically as often as Cron runs.If you face any problems or need our professional services, please email us at [email protected]

Join our Newsletter

Never miss the latest offers, voucher codes and useful articles delivered weekly in your inbox.