我不想使用 crontab 在数据库中安排SQL
查询。PostgreSQL
在终端中,在 root 中,当我运行时:
psql -U postgres -d my_database -h localhost -p 5432 -c "INSERT INTO schema.table (name) VALUES ('Insert with a command from terminal');"
它问我一个密码。所以我添加它:
PGPASSWORD="mypassword" psql -U postgres -d my_database -h localhost -p 5432 -c "INSERT INTO schema.table (name) VALUES ('Insert with a command from terminal and password');"
当我在 crontab 中运行相同的命令时,它没有成功:
0 12 * * * PGPASSWORD="mypassword" psql -U postgres -d my_database -h localhost -p 5432 -c "INSERT INTO schema.table (name) VALUES ('Insert with a command from crontab and password');"
crontab 日志返回我
nano var/log/syslog
(root) CMD (PGPASSWORD="mypassword" psql -U postgres -d my_database -h localhost -p 5432 -c "INSERT INTO schema.table (name) VALUES ('Insert with a command from crontab and password');")
CRON[15504]: (CRON) info (No MTA installed, discarding output)
CRON[15677]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
crontab[15862]: (root) BEGIN EDIT (root)
systemd[1]: session-60285.scope: Succeeded.
crontab[15862]: (root) END EDIT (root)
为什么 crontab 作业不执行 pgsql 命令?如何使用 crontab 安排 SQL 命令?
cron 的一些实现(我认为包括 Debian 附带的那个)允许您在前面的行中设置环境变量:
这必须是一个cron工作吗?由于您正在运行 Debian,因此您可以使用 systemd 的计时器。
要在 systemd 中实现这一点,您将编写一个调度作业的计时器单元和一个运行该作业的服务单元。服务单元可以设置环境变量。
试试看它
sudo systemctl start regularquery.service
是否连接正常。您可以使用 监视输出journalctl -u regularquery.service
。当你高兴时,安排事情sudo systemctl enable --now regularquery.timer
或者,我在以下位置找到了这个
man psql
:这表明这
~/.pgpass
可能是环境变量的一个很好的替代方案。它还建议--no-password
对于非用户会话(即 crontab 或 systemd)是一个很好的开关,因为它永远不会以交互方式暂停提示。