Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › Automation

How to Run a PHP Job Multiple Times a Minute With Cron on Ubuntu

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ubuntu cron cannot schedule a command several times inside one minute: it evaluates crontab entries once per minute, and the minute field only represents values 0 through 59. The reliable pattern is to have cron launch a wrapper once each minute. That wrapper runs the PHP command, waits for a chosen interval, and repeats within the minute. Use the PHP command-line interface, absolute paths, explicit environment settings, logging, and a lock so slow runs do not overlap.

What cron can and cannot schedule

A standard crontab expression has five time fields: minute, hour, day of month, month, and day of week. Ubuntu’s cron implementation examines entries every minute. The minute field accepts 0–59, so cron itself has no seconds field and cannot express a five-minute, 30-second, or other sub-minute interval.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Minute steps are useful only when the interval is a whole number of minutes. For example:

*/10 * * * * /path/to/command

This runs at minutes divisible by 10: 00, 10, 20, 30, 40, and 50 of each hour. It does not create a continuously rolling ten-minute timer. Ubuntu also documents a common trap: 0/35 in the minute field means minute 0 and minute 35 of every hour, not one execution every 35 minutes across hour boundaries.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

For several launches per minute, cron should be treated as the once-per-minute trigger. A shell wrapper, a persistent worker, or a supervised service must provide the shorter interval.

The practical cron-plus-wrapper design

The simplest arrangement is one crontab entry that starts a wrapper at the beginning of every minute:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
* * * * * /usr/local/bin/run-php-job.sh >> /var/log/php-job.log 2>&1

The wrapper invokes the PHP CLI, sleeps for the selected delay, and repeats. If the job should start about every 20 seconds, the wrapper might attempt three starts per minute. If it should start about every 15 seconds, it might attempt four. Those counts are workload decisions; cron does not calculate them for you.

“Every 20 seconds” is approximate. PHP startup time, the job’s own runtime, scheduler delays, and system load all affect the actual start times. A wrapper that sleeps after each invocation spaces starts by approximately runtime plus sleep duration, not by the sleep duration alone. To target a fixed wall-clock cadence, the wrapper must account for elapsed time, as shown below.

A straightforward interval wrapper

Create the wrapper at a stable absolute path:

sudo install -m 0755 /dev/stdin /usr/local/bin/run-php-job.sh <<'EOF'
#!/bin/sh

PHP=/usr/bin/php
SCRIPT=/srv/app/job.php
INTERVAL=20
RUNS=3

n=1
while [ "$n" -le "$RUNS" ]; do
    "$PHP" "$SCRIPT"
    status=$?
    if [ "$status" -ne 0 ]; then
        printf '%s PHP job exited with status %sn' "$(date -Is)" "$status" >&2
    fi
    n=$((n + 1))
    [ "$n" -le "$RUNS" ] && sleep "$INTERVAL"
done
EOF

Replace /srv/app/job.php with the script’s real absolute path. This version makes three attempts and waits 20 seconds between attempts. A long-running PHP process delays the next attempt, so it is suitable only when that behavior is acceptable.

A wrapper that targets minute boundaries

If you want starts near 00, 20, and 40 seconds of each minute, calculate a deadline rather than blindly sleeping after work. This keeps the wrapper inside the minute window when the job finishes quickly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#!/bin/sh

PHP=/usr/bin/php
SCRIPT=/srv/app/job.php
INTERVAL=20
END=$(( $(date +%s) + 60 ))
NEXT=$(date +%s)

while [ "$NEXT" -lt "$END" ]; do
    "$PHP" "$SCRIPT"
    status=$?
    if [ "$status" -ne 0 ]; then
        printf '%s PHP job exited with status %sn' "$(date -Is)" "$status" >&2
    fi

    NEXT=$((NEXT + INTERVAL))
    NOW=$(date +%s)
    WAIT=$((NEXT - NOW))
    [ "$WAIT" -gt 0 ] && sleep "$WAIT"
done

This is still best-effort scheduling, not a real-time guarantee. If one invocation takes longer than the next target, the wrapper does not create a backlog of missed starts; it proceeds to the next loop iteration. Decide explicitly whether that skip behavior is right for the job.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Use PHP’s CLI binary, not a web request

PHP’s CLI SAPI is intended for shell applications. A cron job should execute the PHP file directly rather than making an HTTP request to a web endpoint. Direct CLI execution avoids web-server timeouts, authentication layers, and differences between web and command-line PHP configuration.

Check the binary as the Unix account that will own the cron entry:

command -v php
php -v
php --ini

command -v php shows which executable an interactive shell would select; php -v confirms the version; and php --ini shows the configuration files loaded by the CLI SAPI. Cron has a smaller environment than an interactive shell, so use the discovered absolute path, commonly /usr/bin/php, in the wrapper.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP supports both forms below:

/usr/bin/php /srv/app/job.php
/usr/bin/php -f /srv/app/job.php

Use the form that your script and team standardize on. Ensure the cron user can read the PHP file and every required application file, and can write any output, cache, or temporary directory the job uses.

Install the wrapper and cron entry safely

  1. Choose the Unix account. Run the job as the least-privileged account that can access its files. A user’s crontab runs as that user; it does not inherit your login account’s permissions.
  2. Create the script. Store the wrapper outside a home directory if several administrators need to maintain it, and keep absolute paths in the script.
  3. Make it executable. Use chmod 0755 /usr/local/bin/run-php-job.sh or install it with the mode shown above.
  4. Run it manually as the cron user. Test the exact command, not a shortened interactive equivalent:
sudo -u appuser /usr/local/bin/run-php-job.sh
  1. Edit that user’s crontab. Open it with crontab -e. Add:
* * * * * /usr/local/bin/run-php-job.sh >> /var/log/php-job.log 2>&1
  1. Review the installed entry.
crontab -l
  1. Observe the logs. Wait for a minute boundary, then inspect the wrapper log and the application’s own log. A cron line can be syntactically valid while the PHP process fails because of permissions, a missing environment variable, or a wrong working directory.

If you use /etc/crontab or a file in /etc/cron.d instead, include the username field:

* * * * * appuser /usr/local/bin/run-php-job.sh >> /var/log/php-job.log 2>&1

Do not copy that six-field form into a personal crontab; crontab -e entries do not contain a username column.

Make the cron environment explicit

Cron runs commands through /bin/sh unless the crontab sets a different SHELL. It also does not provide the aliases, shell startup files, working directory, or exported variables that you may rely on interactively. Set every required value explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

For simple settings, define variables at the top of the crontab:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
APP_ENV=production
* * * * * /usr/local/bin/run-php-job.sh >> /var/log/php-job.log 2>&1

For secrets and larger configuration, prefer the application’s protected environment file or a dedicated configuration mechanism rather than placing credentials directly in a world-readable crontab. The wrapper can change to the application’s directory before running PHP if relative paths are unavoidable, but absolute paths are safer:

cd /srv/app || exit 1
exec /usr/bin/php /srv/app/job.php

Always redirect both standard output and standard error. Unredirected output may be mailed by cron, and mail delivery is often not configured or monitored on servers.

Prevent overlapping executions

A new minute can begin while the previous wrapper is still running. Without a guard, two PHP processes may update the same rows, send duplicate messages, or compete for a file. Choose an overlap policy before enabling the schedule: skip a launch, queue work, or allow concurrent processing with application-level coordination.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Shell lock with flock

On Ubuntu, a shell wrapper can use the flock utility to implement the skip policy:

#!/bin/sh

LOCK=/run/user/1001/php-job.lock
PHP=/usr/bin/php
SCRIPT=/srv/app/job.php

exec 9>"$LOCK"
if ! flock -n 9; then
    printf '%s another wrapper is still runningn' "$(date -Is)" >&2
    exit 0
fi

n=1
while [ "$n" -le 3 ]; do
    "$PHP" "$SCRIPT"
    status=$?
    [ "$status" -eq 0 ] || printf '%s PHP job exited with status %sn' "$(date -Is)" "$status" >&2
    n=$((n + 1))
    [ "$n" -le 3 ] && sleep 20
done

Use a lock location writable by the cron user and appropriate to the host’s account setup. A lock file alone is not a lock; the process must hold an open file descriptor with flock for the duration of the work.

Lock inside PHP

If several entry points can start the same job, put the guard in PHP as well. PHP’s flock() provides an advisory lock, meaning every cooperating invocation must open the same lock file and honor the convention:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
<?php
$lockPath = '/var/lock/my-app-php-job.lock';
$handle = fopen($lockPath, 'c');
if ($handle === false) {
    fwrite(STDERR, "Cannot open lock filen");
    exit(1);
}

if (!flock($handle, LOCK_EX | LOCK_NB)) {
    fwrite(STDOUT, "Another invocation is activen");
    exit(0);
}

try {
    // Job work goes here.
} finally {
    flock($handle, LOCK_UN);
    fclose($handle);
}

The account must be able to create or open the lock file. A PHP lock protects only processes that use that same advisory lock; it cannot stop an unrelated process from modifying the data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decide what a failure means

A wrapper needs an explicit failure policy. The basic loop above logs a non-zero exit status and continues to later attempts. That is useful when each invocation is independent, but it can be dangerous when a failed first run makes later runs invalid.

  • Abort the minute: exit immediately after a non-zero status when later attempts should not run.
  • Continue: record the status and keep the cadence when each attempt handles separate work.
  • Retry: perform a bounded retry with backoff, then record a final failure. Avoid an unbounded retry loop inside a once-per-minute cron launch.
  • Queue: write durable work items to a database or queue and let a worker process them. This is preferable when missed work must not disappear.

Return meaningful exit codes from the PHP script and include timestamps, identifiers, and error details in the application log. Cron’s redirection captures output, but it does not provide durable retry or alerting by itself.

Logging, permissions, and rotation

The redirection target must be writable by the cron user. A root-owned file in /var/log may cause the wrapper to fail before PHP starts. Create the file and directory with ownership and permissions that match the account, or log to an application directory managed by the service.

Repeated launches can grow a log quickly. Configure the host’s normal log-rotation mechanism, or direct structured application logs to the platform’s logging service. Rotation must preserve write access after a new file is created. Include enough context to distinguish wrapper messages from PHP output, especially when multiple jobs share a host.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How this approach compares with alternatives

Approach Cadence Lifecycle and failure handling Best fit
Cron entry alone One-minute granularity Simple launch; no sub-minute loop Whole-minute schedules and lightweight maintenance
Cron plus shell wrapper Approximate sub-minute spacing using sleep Easy to deploy; you must define locking, retries, and logging Small jobs that can tolerate best-effort timing
Persistent worker or supervised service Can maintain a tighter cadence without starting PHP each time Stronger restart, health, and failure control; more deployment work High-frequency or mission-critical processing
Queue-backed worker Driven by queued work rather than a fixed launch interval Durable retries and explicit concurrency controls Work that must survive restarts or never be silently skipped

Repeated CLI launches incur PHP process startup overhead. A persistent worker can reduce that overhead, but it introduces deployment, memory-leak, restart, and monitoring concerns. Choose the simplest architecture that meets the job’s timing and durability requirements.

Troubleshoot the common failure modes

Nothing runs

  • Run crontab -l as the intended user and verify the line was installed in that user’s crontab.
  • Run the wrapper manually with sudo -u appuser and capture its exit status.
  • Check that the wrapper has an executable shebang and mode 0755.
  • Use absolute paths for PHP, the script, configuration files, and log destinations.
  • Inspect the host’s cron service logs as well as the redirected application log.

PHP works interactively but fails in cron

  • Compare php --ini for the interactive account with the CLI configuration used by cron.
  • Set PATH, application environment variables, and working directory explicitly.
  • Check permissions on the script, dependencies, lock file, log, and any data directories.
  • Remember that cron invokes /bin/sh; bash-only syntax requires a bash shebang and an installed bash interpreter.

Runs overlap or duplicate work appears

  • Confirm every launch path uses the same shell or PHP lock file.
  • Check whether the wrapper itself lasts longer than a minute.
  • Decide whether skipping, queuing, or concurrent processing is the intended policy; a lock implements skipping, not queuing.

The cadence drifts

  • Measure the PHP runtime. A sleep-after-run loop spaces starts by runtime plus sleep.
  • Use the elapsed-time wrapper when starts should align with approximate positions within each minute.
  • For strict timing, use a supervised worker or another scheduler designed for that lifecycle; cron is not a real-time scheduler.

When cron is the wrong tool

Cron plus a wrapper is appropriate for lightweight periodic work on a machine that remains available. It is not a durable scheduler: a host shutdown, reboot, process termination, or PHP failure can leave an invocation unfinished, and cron does not automatically create a durable record of missed work.

Use a supervised service, queue worker, or systemd-based worker architecture when the job requires strict sub-minute timing, restart supervision, durable state across host restarts, coordinated retries, or sustained throughput. Those systems add configuration and operational responsibility, but they make lifecycle and failure behavior explicit instead of hiding it inside a shell loop.

A production-readiness checklist

  • The job is executed with the PHP CLI and an absolute binary path.
  • The wrapper and PHP script use absolute paths and an explicit working directory where needed.
  • The cron account, file permissions, environment variables, and CLI configuration have been tested together.
  • The once-per-minute crontab entry redirects both output streams to a writable, rotated log.
  • A lock prevents unsafe overlap, and every cooperating process honors the same advisory lock.
  • The wrapper’s interval, number of attempts, deadline behavior, and failure policy are documented.
  • Manual and cron-triggered runs have been observed at a minute boundary.
  • The architecture has been reconsidered if work must be durable, strictly timed, or high-throughput.

Frequently Asked Questions

Can I write a cron expression for every 30 seconds?

No. Ubuntu cron examines entries once per minute and has no seconds field. Start a once-per-minute wrapper and perform the sub-minute repetition there, or use a worker or service designed for that cadence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does */10 mean every ten minutes continuously?

It runs at minute values divisible by 10 within each hour: 00, 10, 20, 30, 40, and 50. Minute-field steps do not create a rolling interval across hour boundaries.

Should the cron line call a PHP web URL?

Use the PHP CLI directly, such as /usr/bin/php /srv/app/job.php. The CLI SAPI is intended for shell applications and avoids web-server request limits.

Why does the next run start later than the sleep interval?

If the wrapper sleeps after PHP exits, the spacing includes the PHP runtime plus the sleep duration. Use elapsed-time scheduling for approximate minute positions, or a persistent worker for tighter control.

The Bottom Line

Use cron as a once-per-minute trigger, not as a sub-minute scheduler. A carefully written wrapper can run the PHP CLI several times during that minute, but absolute paths, explicit environment settings, logging, locking, and a clear failure policy determine whether the arrangement is safe. Move to a supervised worker or queue when timing, durability, or throughput matters more than cron’s simplicity.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

AutomationCronLinux serverPHPShell ScriptingUbuntu

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.