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:
- Cron will run only after a page hit. If there’s no traffic the cron is not triggered.
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php if ($argv[1]=='sofij398uw8wf') { //set the working directory chdir('/var/www/example.com/html/folder/'); define('DRUPAL_ROOT', getcwd()); $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; $base_url = 'https://www.example.com/folder'; include_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); global $user; $original_user = $user; $old_state = drupal_save_session(); drupal_save_session(FALSE); $user = user_load(1); // Take your action here where you pretend to be the user with UID = 1 (typically the admin) // If your code fails, it's not a problem because the session will not be saved drupal_cron_run(); //drupal_flush_all_caches(); //in case we want to wipe the cache $user = $original_user; drupal_save_session($old_state); // From here on the $user is back to normal so it's OK for the session to be saved } ?> |
A few notes about the above code:
- I’m using $argv to read passed parameters since I’m running this through command line php:
1php -q cronit.php sofij398uw8wf - The script didn’t execute using wget / curl (adjusted). It only works running in php as above.
- The parameter used (‘sofij398uw8wf’) is used as a key to avoid unwanted visitors.
- The user handling (switching to admin and back) is also a security measure to avoid granting admin permissions to unwanted visitors.
- There is a line for flushing all cache:
1drupal_flush_all_caches();
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.