Get Drush to run Drupal cron regularly using crontab

Drush can Drupal cron without the need of accessing http://www.yoursite.com/cron.php?cron_key=<key>. This means we can safely remove or redirect cron.php to 404 Not Found in our .htaccess:

  
RewriteRule cron.php / [R=404,L]
  

To make our crontab script simple, we will use Drush's site aliases. Example if we are running multiple sites in our server: yoursite1.com, yoursite2.com and yoursite3.com we can assign alias @site1, @site2 and @site3 respectively. To do this:

  
vi ~/.drush/aliases.drushrc.php
  

If our Drupal installation path is at "/var/www" we can have something like this inside aliases.drushrc.php:

  
<?php
/**
* @file aliases.drushrc.php
*/
$aliases['site1'] = array (
 'uri' => 'yoursite1.com',
 'root' => '/var/www',
);
$aliases['site2'] = array (
 'uri' => 'yoursite2.com',
 'root' => '/var/www',
);
$aliases['site3'] = array (
 'uri' => 'yoursite3.com',
 'root' => '/var/www',
);
  

Note: There are many options available in Drush site aliases feature, you may want to explore the example file example.aliases.drushrc.php under the examples folder in your drush distribution.

Now, our Drush commands becomes simple. Before if we want to display the status of yoursite1.com, we execute:

  
drush -l yoursite1.com status
  

Now with Drush alias, we can execute:

  
drush @site1 status
  

Lets register our Drupal cron tasks to crontab. First, we need to identify the full path of our Drush. Executing the command below will give the path:

  
which drush
  

... and my server display:

  
/root/.composer/vendor/bin/drush
  

Edit the crontab:

  
crontab -e
  

... and write something like this in our crontab script:

  
*/30 * * * * /root/.composer/vendor/bin/drush @site1 cron
0 */3 * * * /root/.composer/vendor/bin/drush @site2 cron
0 3 * * 1-5 /root/.composer/vendor/bin/drush @site3 cron
  

The script above means that the Drupal cron task for yoursite1.com will execute every 30 minutes, yoursite2.com executes every three hours and yoursite3.com executes at 3:00 of every working day.

Lastly, set the "Run cron every" to "Never" at cron settings page our Drupal sites: yoursite1.com/admin/config/system/cron, yoursite2.com/admin/config/system/cron and yoursite3.com/admin/config/system/cron

Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.