从 crontab 执行的脚本未运行

从 crontab 执行的脚本未运行

大家好,

我有一个安装了 Ubuntu 操作系统和 MySQL 的 Docker 容器。

我需要每天重启一次 MySQL,通常使用 cron 来执行此操作。

当我通过 CLI 运行脚本时,脚本在 Docker 容器内完美运行。

脚本内容:

#!/bin/bash

echo "Stopping MySQL" 
service mysql stop 
sleep 15s 
echo "Starting MySQL" 
service mysql start
sleep 10s 
echo "MySql Restarted" 
service mysql status 
sleep 10s

从 CLI 运行时记录,使用./mysqlRestart >>/var/log/mysqlRestart 2>&1:

Stopping MySQL

Stopping MySQL database server mysqld ...done. 
Starting MySQL
Starting MySQL database server mysqld su: warning: cannot change directory to /nonexistent: No such file or directory ...done. 
MySql Restarted
/usr/bin/mysqladmin Ver 8.0.30-0ubuntu0.20.04.2 for Linux on x86_64 ((Ubuntu)) Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Server version 8.0.30-0ubuntu0.20.04.2 Protocol version 10 Connection Localhost via UNIX socket UNIX socket /var/run/mysqld/mysqld.sock Uptime: 11 sec

Threads: 2 Questions: 8 Slow queries: 0 Opens: 119 Flush tables: 3 Open tables: 38 Queries per second avg: 0.727

crontab -e entry: */5 * * * * bash /usr/local/bin/mysqlRestart >>/var/log/mysqlRestart 2>&1

从 crontab 运行时记录:

Stopping MySQL /usr/local/bin/mysqlRestart: line 4: service: command not found 
Starting MySQL /usr/local/bin/mysqlRestart: line 7: service: command not found 
MySql Restarted /usr/local/bin/mysqlRestart: line 10: service: command not found

答案1

运行 cron 作业的超级用户帐户不知道在哪里找到service。您将需要使用命令的完整路径:

/usr/sbin/service mysql restart

不过,您可能需要仔细检查运行时间,因为每五分钟检查一次有点过分。如果您的数据库每天都需要重新启动,这通常意味着:

  • 低效的 SQL 查询
  • 内存不足
  • I/O 性能不佳

如果可能的话,可能值得考虑优化 Docker 容器设置,以减少此类解决方法的需要

相关内容