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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A reliable cron monitor should ask MySQL whether it can answer, restart the service only when the check fails, and leave enough evidence to diagnose the next failure. Use mysqladmin ping with an explicit connection target, protected credentials, and a short timeout; use the host’s service manager—usually systemctl—for recovery. Add a lock, timestamped logging, a repeated-failure counter, and an alert path so a crash does not become a silent restart loop.

The procedure below covers systemd hosts using either the mysqld or mysql unit name, explains what the ping exit status really means, and shows how to test the job under cron’s restricted environment.

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.

What the cron check should measure

Cron itself only starts a command on a schedule. It does not understand whether MySQL is healthy, whether a process is listening, or whether a restart succeeded. The monitor must make those decisions explicitly.

Use mysqladmin ping for server reachability

Oracle’s MySQL 8.0 Reference Manual documents mysqladmin ping as the availability check. It returns exit status 0 when the server is running and answering, and status 1 when the server is not running. That makes it suitable for shell logic:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
  • Status 0: treat the check as successful and do not restart.
  • A nonzero status: record the command output and investigate or invoke recovery according to your policy.

An important distinction is authentication. MySQL can return “Access denied” while still returning status 0, because the server is reachable and rejected the connection. A bad password is therefore not evidence that the daemon stopped. If your command fails because it cannot reach the configured host or socket, the failure may instead be a wrong connection target, DNS problem, firewall, permissions issue, or a server that is starting slowly.

Use systemctl for process and unit state

systemctl status reports the state of the registered service unit and its recent journal output. It answers a different question from mysqladmin ping: a unit can be active while the server is temporarily unable to accept a connection, and a reachable server can be running under a unit name you did not expect. A sound monitor uses the ping as its application-level signal and consults systemd for control and diagnosis.

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

Identify the service manager and unit name first

Do not install a cron job until you know how this host starts MySQL. On systemd systems, Oracle documents commands in the form systemctl {start|stop|restart|status} mysqld. RPM-family installations commonly use mysqld; Debian-family installations and some SUSE Linux Enterprise Server systems may use mysql.

Check both likely unit names

systemctl status mysqld --no-pager
systemctl status mysql --no-pager

Use the name that identifies the installed server. If one command reports that the unit does not exist and the other shows a loaded service, set that exact name in the script. Also check whether the unit is enabled and what executable it starts:

systemctl is-enabled mysqld
systemctl cat mysqld

Replace mysqld with mysql where appropriate. The unit file can reveal a nonstandard data directory, socket, or startup option that explains why a default ping command cannot connect.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Hosts without systemd

Some Unix-like systems use the mysqld_safe launcher or the mysql.server script instead of systemd. In that case, the recovery command must be the host’s established startup script, and the cron account needs the same environment, paths, and permissions used by that script. Do not call an arbitrary mysqld binary directly unless you also understand its data directory, configuration file, ownership, and shutdown behavior.

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

Prepare a safe connection for cron

Interactive shell settings are not inherited by cron. Use absolute command paths, specify the connection target, and store credentials in a protected mechanism.

Choose an explicit host or socket

For a local TCP connection, an example check is:

/usr/bin/mysqladmin --login-path=cron --host=127.0.0.1 --port=3306 --connect-timeout=5 ping

If the installation is socket-only, use the actual socket path instead of the host and port:

/usr/bin/mysqladmin --login-path=cron --socket=/run/mysqld/mysqld.sock --connect-timeout=5 ping

The path in the second example is illustrative; obtain the real socket from the unit configuration, MySQL configuration, or a successful interactive connection. A short timeout prevents one hung network or socket attempt from occupying the cron process indefinitely.

Keep credentials out of the command line

Do not put a password directly after -p in a crontab or script. Use a MySQL login path created with mysql_config_editor, or a dedicated option file readable only by the monitoring account. A login path named cron is referenced with --login-path=cron; the account, host, and password remain in MySQL’s protected login-path storage rather than in the process arguments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

If you use an option file instead, give it restrictive permissions such as mode 600, verify its owner, and reference it explicitly with --defaults-extra-file=/path/to/file. Ensure the file is readable by the user running the cron entry and by no broader group than necessary.

Decide which account runs recovery

Restarting a system service normally requires root or a narrowly delegated privilege. The simplest arrangement is a root crontab with root-owned script and log paths. If a service account must run the check, grant only the required restart operation through your platform’s privilege mechanism and test it non-interactively. Cron cannot answer a password prompt, and a sudo command that works in your terminal can fail when no terminal or interactive environment is present.

Install a monitor-and-restart script

The following POSIX shell example uses a directory as a lock, records every check, counts consecutive failures, asks systemd for status, restarts the selected unit, and verifies the server afterward. The failure threshold of three is an example policy; change it to match your recovery time and alerting requirements.

#!/bin/sh

PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077

LOG=/var/log/mysql-cron-monitor.log
LOCK=/run/mysql-cron-monitor.lock
STATE=/run/mysql-cron-monitor.failures
SERVICE=mysqld
MYSQLADMIN=/usr/bin/mysqladmin
MAX_FAILURES=3

now() {
    date '+%Y-%m-%dT%H:%M:%S%z'
}

log() {
    printf '%s %sn' "$(now)" "$*" >> "$LOG"
}

# A second invocation exits instead of running concurrently.
if ! mkdir "$LOCK" 2>/dev/null; then
    exit 0
fi
trap 'rmdir "$LOCK"' EXIT HUP INT TERM

PING="$MYSQLADMIN --login-path=cron --host=127.0.0.1 --port=3306 --connect-timeout=5 ping"

if output=$(sh -c "$PING" 2>&1); then
    log "ping ok: $output"
    rm -f "$STATE"
    exit 0
fi

ping_status=$?
count=$(cat "$STATE" 2>/dev/null || printf '0')
case "$count" in
    ''|*[!0-9]*) count=0 ;;
esac
count=$((count + 1))
printf '%sn' "$count" > "$STATE"
log "ping failed (exit $ping_status, consecutive failure $count): $output"

# Preserve unit diagnostics even when status returns nonzero.
systemctl status "$SERVICE" --no-pager >> "$LOG" 2>&1 || true

if systemctl restart "$SERVICE" >> "$LOG" 2>&1; then
    log "restart command completed for $SERVICE"
    sleep 2
    if output=$($MYSQLADMIN --login-path=cron --host=127.0.0.1 --port=3306 --connect-timeout=5 ping 2>&1); then
        log "ping succeeded after restart: $output"
        rm -f "$STATE"
        exit 0
    fi
    log "ping still failed after restart: $output"
else
    log "restart command failed for $SERVICE"
fi

if [ "$count" -ge "$MAX_FAILURES" ]; then
    message="MySQL monitor reached $count consecutive failures for $SERVICE"
    log "ALERT: $message"
    logger -p daemon.err -t mysql-cron-monitor "$message" 2>/dev/null || true
    printf '%s %sn' "$(now)" "$message" >&2
fi

exit 1

Change SERVICE=mysqld to SERVICE=mysql when that is the unit discovered earlier. Change the host, port, socket, or login path to the values that work manually. The script assumes systemctl, logger, and the selected log directories exist; adapt those paths if the distribution places them elsewhere.

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

Why the lock matters

A cron interval can be shorter than a slow startup or a blocked command. Without a lock, several copies can all decide that MySQL is down and issue overlapping restarts. The mkdir operation is atomic: the first process creates the directory, and later processes exit. The exit trap removes it when the script finishes. If the host can lose power while the lock exists, put the lock in a volatile runtime directory such as /run, or add an administrator-reviewed stale-lock cleanup policy rather than deleting locks blindly.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Why the script logs before and after recovery

The log captures the timestamp, ping output, exit status, unit status, restart result, and post-restart check. That sequence distinguishes a stopped service from a failed restart, a reachable server with rejected credentials, and a server that needs more than two seconds to recover. Restrict the log’s permissions because command output can contain connection details.

Schedule the job in cron

Install the script at a root-owned path, make it executable, and run it from the same account that will own the lock, log, and service operation:

install -o root -g root -m 0750 mysql-cron-monitor /usr/local/sbin/mysql-cron-monitor

Edit the appropriate crontab with crontab -e as that account. This example checks every five minutes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
MAILTO=admin@example.net
*/5 * * * * /usr/local/sbin/mysql-cron-monitor

The five-minute interval is a scheduling choice, not a MySQL requirement. A shorter interval detects failures sooner but increases command and restart pressure; a longer interval reduces overhead but leaves an outage undetected for longer. Cron mails output only when the local cron implementation and mail transport are configured. Keep the explicit logger call or connect the alert branch to your approved notification system if email is not dependable.

Test it exactly as cron will run it

  1. Run the ping command manually with the final login path, host or socket, timeout, and absolute path. Confirm that a healthy server returns shell status 0.
  2. Run the complete script from the same user and with a minimal environment, for example with an explicit PATH. Do not rely on aliases, shell profiles, exported variables, or an SSH agent.
  3. Inspect the dedicated log and the system journal after a successful run. Verify that the failure-state file is removed after recovery.
  4. Perform a controlled test in a maintenance window by stopping the selected unit with the normal service manager, then run the script manually. Confirm that it records the failure, restarts the correct unit, and obtains a successful ping afterward.
  5. Test a negative case without stopping MySQL: temporarily point the check at an invalid socket or port in a copy of the script. Confirm that the monitor logs the connection error and that you understand whether your chosen policy would restart or alert.
  6. Restore the real connection settings, wait for at least one scheduled invocation, and verify the cron log, mail output, and alert destination.

Never test by killing the daemon on a production host without an approved maintenance procedure. A restart can trigger crash recovery, replication lag, application errors, or an extended outage.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Interpret outcomes before changing the policy

Observation What it establishes Recommended action
mysqladmin ping exits 0 The server answered the request. It may still reject the supplied account with “Access denied.” Do not restart. Investigate authentication separately if the application cannot log in.
Ping exits nonzero and systemctl status shows inactive or failed The registered service is not running normally. Capture status output, restart the verified unit, and check the post-restart ping.
Ping exits nonzero but the unit is active The process is running according to systemd, but the configured endpoint did not answer. Check socket or port, DNS, firewall, permissions, startup/recovery delay, and MySQL logs before permitting repeated restarts.
Restart returns success but the next ping fails systemd accepted the restart request; it does not prove that MySQL completed startup. Record the unit journal and MySQL error log, allow for recovery time, and escalate after the configured consecutive-failure threshold.
Several consecutive failures The problem is persistent or the monitor is misconfigured. Alert an operator. Do not let cron silently repeat a restart loop.

Choose between ping and systemd checks

Neither signal replaces the other. Select the primary check according to the failure you need to detect, then keep the other as supporting evidence.

Approach Health signal Recovery authority Coverage and limitations
mysqladmin ping Application-level reachability of the configured MySQL endpoint. None by itself; it only reports status. Uses documented shell exit codes, but can be misdirected by a wrong host, socket, credentials, or timeout.
systemctl status Process and unit state known to systemd, plus recent service diagnostics. Can invoke systemctl restart for the registered unit. Unit names differ by distribution, and an active unit does not guarantee that clients can complete a connection.
Direct mysqld_safe or mysql.server control Depends on the script and process checks provided by that installation. The launcher or init script used by the host. Useful where systemd is absent, but requires exact knowledge of paths, environment, configuration, ownership, and shutdown behavior.

Troubleshoot common failures

The script says the unit does not exist

Re-run systemctl status mysqld and systemctl status mysql. Set the script’s SERVICE variable to the loaded unit. If neither exists, the host may use a different package, a container, or a non-systemd startup method; identify that mechanism before automating recovery.

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

Ping reports access denied

Do not restart solely because the text contains “Access denied.” The documented ping behavior treats a reachable server that refuses authentication as a successful availability check. Correct the login path or option file, account privileges, host restriction, or password, then test again. Keep the service-restart decision tied to the command’s exit status and corroborating service state.

Ping cannot find the socket

Compare the script’s socket path with the path in the active MySQL configuration and the systemd unit. A server can be healthy while listening on a different socket or TCP port. Use an explicit, verified endpoint rather than relying on defaults that differ between interactive shells and cron.

The command works interactively but fails from cron

Check the absolute path to mysqladmin, the login-path or option-file permissions, the cron user, and the script’s PATH. Cron does not load your shell profile. If the restart uses sudo, verify that the rule permits non-interactive execution and that no password prompt is required.

MySQL needs longer to recover

Crash recovery, storage checks, or a large data set can make the post-restart ping fail briefly. The script’s two-second verification delay is only an example. Increase it or add a bounded retry sequence based on observed recovery time, while retaining a maximum duration and an alert. Do not respond to a slow but progressing recovery with overlapping restarts.

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

The host enters a restart loop

Repeated crashes can result from a full disk, invalid configuration, damaged permissions, resource exhaustion, or an application-triggered failure. Inspect the systemd journal, MySQL error log, disk capacity, ownership, and recent configuration changes. Keep the consecutive-failure counter and alert branch enabled; automation should expose the underlying fault rather than hide it.

Operational hardening checklist

  • Verify the actual unit name and startup mechanism before deployment.
  • Use an explicit host or socket, a short connection timeout, and a protected login path or option file.
  • Set an absolute PATH and command paths in the script.
  • Run with the least privilege that can perform the required status and restart operations.
  • Protect the script, credential store, lock, state file, and log from unauthorized modification or reading.
  • Prevent overlap with an atomic lock and ensure it is cleaned up on normal exit.
  • Log timestamps, ping output, exit status, service status, restart result, and post-restart verification.
  • Use a consecutive-failure threshold and an alert route; do not rely on restarts alone.
  • Test healthy, stopped, misdirected-endpoint, slow-recovery, and permission-failure cases.
  • Review the monitor after package upgrades, unit-file changes, socket changes, or migration from one distribution family to another.

What a dependable cron monitor looks like

The essential sequence is short: ask the configured MySQL endpoint with mysqladmin ping, interpret its documented exit status, consult the verified service unit when the check fails, restart through that service manager, and ping again. Locking, protected credentials, explicit paths, logs, and repeated-failure alerts turn that sequence into an operational control rather than a one-line restart loop. If the host does not use systemd, apply the same logic to its established mysqld_safe or mysql.server mechanism and test it under the exact cron account and environment.

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.