Search code examples
phplinuxcron

How to run Cronjobs more often than once per minute?


I created a Email-Queue database table. I will insert all Emails my PHP application needs to send into this table.

Another PHP script will then look for all unsent Emails and sends them.

I run this script using cronjobs. Unfortunately cronjobs can run only at a maximum of once per minute. So in the worst-case a user has to wait one minute until his Email is really going to be sent.

My current idea for a workaround is calling the script with an addtional sleep parameter and duplicating the cronjobs.

Example:

* * * * * curl emails.php?sleep=0 >/dev/null 2>&1
* * * * * curl emails.php?sleep=10 >/dev/null 2>&1
* * * * * curl emails.php?sleep=20 >/dev/null 2>&1
* * * * * curl emails.php?sleep=30 >/dev/null 2>&1
* * * * * curl emails.php?sleep=40 >/dev/null 2>&1
* * * * * curl emails.php?sleep=50 >/dev/null 2>&1

In the above example the script would run every 10 seconds. The first line of the emails.php Script would be:

sleep($_REQUEST['sleep']);

Solution

  • For starters, I'd recommend using the command line version of PHP rather than using curl to call a script. You can then create a PHP script with a sensible lifetime that isn't constrained by having to output a response within a given time period.

    As such, you can then simply sleep/check for emails/transmit/sleep, etc. within the PHP script rather than needlessly using cron.

    Additionally, I'd take care to ensure that multiple PHP scripts aren't operating on the database table at the same time, either by using a pid file or database setting approach (if a given file/setting exists/is set, abort processing) or by sensibly timing the cron job and limiting the maximum processing time of the script by checking how long it's been running for prior to beginning the "check for emails" portion of the cycle.