Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Run PHP Job Multiple Times a Minute with Cron on Ubuntu

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide explains how to run a PHP script more often than once per minute on Ubuntu using cron. Standard cron only supports minute-level scheduling, but with a simple loop inside the cron job, you can run the script every 30, 15, or even 5 seconds. You'll need a Ubuntu server with PHP installed and a PHP script you want to execute periodically.

What You'll Need

  • A Ubuntu server (20.04 or later) with sudo access.
  • PHP CLI installed (check with php -v).
  • A PHP script that you want to run repeatedly (e.g., /var/www/scripts/job.php).
  • Basic familiarity with the terminal and crontab.

Step-by-Step

  1. Verify PHP CLI works. Run php -v in your terminal. If you see a version number, you're ready. If not, install PHP CLI with sudo apt update && sudo apt install php-cli.
  2. Create your PHP script. Write or place your PHP script somewhere accessible, for example /home/username/job.php. Make sure it's executable or callable with php /path/to/job.php. Test it manually with php /path/to/job.php to confirm it runs without errors.
  3. Open your crontab. Run crontab -e to edit your user's cron jobs. If you need system-wide scheduling, use sudo crontab -e instead.
  4. Add a cron line that runs every minute. Start by adding a line that runs your PHP script every minute. For example:
    * * * * * php /home/username/job.php
    This is your baseline. Test it by waiting a minute and checking if the script runs (e.g., by logging to a file).
  5. Modify the cron line to run multiple times per minute. Replace the simple command with a loop that runs the script a set number of times with a sleep between each run. For example, to run every 20 seconds (3 times per minute):
    * * * * * for i in 1 2 3; do php /home/username/job.php; sleep 20; done
    This runs the script, waits 20 seconds, runs again, waits 20 seconds, runs a third time, and then the minute ends. Adjust the count and sleep to achieve your desired interval.
  6. For even more frequent runs (e.g., every 10 seconds), use a loop with 6 iterations and sleep 10:
    * * * * * for i in $(seq 1 6); do php /home/username/job.php; sleep 10; done
    Note: The loop must finish within the minute, so ensure your script's execution time plus the sleep times total less than 60 seconds.
  7. Redirect output and errors (optional but recommended). To avoid cron emailing you every time, add output redirection:
    * * * * * for i in 1 2 3; do php /home/username/job.php >> /tmp/job.log 2>&1; sleep 20; done
    This appends both normal output and errors to /tmp/job.log.
  8. Save and test. Save the crontab file. Wait for the next minute to tick over, then check your log or confirm the script's effects. If you don't see runs, check the log for errors.
  9. Adjust for long-running scripts. If your PHP script takes more than a few seconds, reduce the number of runs per minute or increase the sleep to avoid overlapping executions. Overlap can cause resource contention or duplicate work.

Common Mistakes

  • Forgetting that cron runs from the user's home directory. Always use absolute paths in your cron command and inside the PHP script (e.g., for file includes).
  • Not accounting for script execution time. If your script takes 25 seconds and you set sleep 20, the loop will take 25+20+25+20+25 = 115 seconds, which exceeds a minute, so cron will skip the next minute's run. Keep total loop time under 60 seconds.
  • Using relative paths for PHP includes. Cron's environment has a minimal PATH. Use absolute paths like /home/username/job.php and inside PHP use __DIR__ for includes.
  • Not making the script executable. While you can call php script.php, if you try ./script.php without a shebang and executable permission, it will fail. Stick to php /path/to/script.php.
  • Ignoring output. Without redirection, cron sends output to email, which may go to a mailbox you never check. Redirect to a file to see errors.

Tips

  • Use a shell script wrapper for complex logic. Instead of cramming a loop into cron, create a shell script (e.g., run_multiple.sh) that contains the loop, then have cron call that script. It's cleaner and easier to edit.
  • Consider using a dedicated task scheduler. If you need sub-minute scheduling frequently, tools like systemd timers with OnCalendar= can handle seconds, or you can use a daemon like supervisord to run a PHP loop continuously.
  • Log timestamps. Inside your PHP script, add error_log(date('Y-m-d H:i:s').' - ran'); to see exactly when each run happens.
  • Test with a simple script first. Create a test PHP file that just writes the current time to a log, then verify the timing before running your real job.
  • Use flock to prevent overlapping runs. If your script could take longer than the interval, wrap the PHP call with flock -n /tmp/job.lock to skip if a previous run is still going.

Troubleshooting

  • The script doesn't run at all. Check the cron syntax with crontab -l. Verify that the PHP path is correct. Test the command manually in the terminal. Check the log file for errors.
  • The script runs once per minute but not multiple times. Ensure your loop is correct. A common mistake is using sleep 20 but having 4 iterations, which totals 80 seconds, so the loop gets cut off. Recalculate the sleep time.
  • PHP errors are not visible. Add 2>&1 to the redirection to capture stderr. Also, check PHP's error log with php -i | grep error_log to see where PHP logs errors.
  • Cron runs but nothing happens. Check if the script's working directory matters. If the script relies on relative paths, use cd /path/to/dir && php script.php in the cron command.
  • The loop runs but the script's effects are delayed. This could be due to PHP's output buffering. If you're writing to a file, use file_put_contents with LOCK_EX to ensure immediate writes.
  • System logs show cron errors. Check /var/log/syslog for cron entries. Look for lines like CRON: (user) CMD (command) to confirm the command is being executed.

Frequently Asked Questions

Can I run a PHP script every second with cron?

Not reliably with cron alone. The loop method works for intervals of a few seconds, but for true per-second execution, you'd need a continuous loop in a daemon or a tool like systemd timers with OnCalendar=.

Will the loop method cause overlapping executions if the script takes longer than the sleep?

Yes. If your script takes 30 seconds and you set sleep 20, the loop will run 30+20+30 = 80 seconds, exceeding the minute. The next cron run will be skipped, and you might get overlapping executions if the script is still running when the next loop starts.

How do I stop the cron job?

Edit your crontab with crontab -e and comment out the line with # or delete it. Then save. The changes take effect immediately.

Can I use this method to run a PHP script every 30 seconds?

Yes. Use a loop with 2 iterations and sleep 30. For example: * * * * * for i in 1 2; do php /path/to/job.php; sleep 30; done. Ensure the script's execution time is minimal.

Why does cron not support seconds directly?

Cron's design is for minute-level scheduling. The loop method is a workaround. For more precise scheduling, use systemd timers or a dedicated job scheduler like Jenkins.

What if my PHP script needs to run only during business hours?

You can combine the loop with cron's hour restrictions. For example, to run every 20 seconds between 9 AM and 5 PM Monday to Friday: * 9-17 * * 1-5 for i in 1 2 3; do php /path/to/job.php; sleep 20; done.