Running the Drupal cron job and flushing cache from the Linux cron

Working with Drupal 7 our default initial setup was running Drupal’s cron using the build-in cron mechanism (poorman’s cron). There are several downsides to this, mainly:

  1. Cron will run only after a page hit. If there’s no traffic the cron is not triggered.
  2. The addition of cron to a page load adds time and resources required for the request – slow response and might even exhaust resources.

So moving to the server’s cron was obvious.
First I tried the default setup as recommended and tried using wget / curl / lynx but it was not triggering the cron.  You can when cron was last executed by going to the cron page in Drupal’s admin -> Configuration -> Cron.

After checking what was going on I found out that cron was running only for logged in users, not anonymous.  So I had to emulate an admin user, run cron and watch for security holes which might grant admin rights to hackers.  I came up with the following script:

A few notes about the above code:

  1. I’m using $argv to read passed parameters since I’m running this through command line php:
  2. The script didn’t execute using wget / curl (adjusted). It only works running in php as above.
  3. The parameter used (‘sofij398uw8wf’) is used as a key to avoid unwanted visitors.
  4. The user handling (switching to admin and back) is also a security measure to avoid granting admin permissions to unwanted visitors.
  5. There is a line for flushing all cache:

    it’s commented out. I recommend running it in its own cron job, separating between the two.

If you are less familiar with setting a cron job in Linux please read my post – Setting a cron job in Linux

For help setting up your cron jobs please comment below or contact me using the form to the right.

Leave a Reply

Your email address will not be published. Required fields are marked *