Debian -- crontab を使用した SQL クエリのスケジュール

Debian -- crontab を使用した SQL クエリのスケジュール

SQLデータベースでクエリをスケジュールするためにcrontabを使用したくありません。PostgreSQL

ターミナルのルートで以下を実行すると:

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コマンドをスケジュールする方法は?

ベストアンサー1

いくつかのcron実装(Debianに付属の実装を含む)を使用すると、最初の数行で環境変数を設定できます。

PGPASSWORD="mypassword" 
0 12 * * * 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');"

クローンの仕事でなければなりませんか? Debian を実行しているので、systemd のタイマーを使用できます。

systemdでこの機能を実装するには、タスクをスケジュールするタイマーデバイスとタスクを実行するサービスデバイスを作成する必要があります。サービスユニットは環境変数を設定できます。

#/etc/systemd/system/regularquery.timer
[Unit]
Description="Timer to run SQL query"
After=postgresql.service

[Timer]
OnCalendar=*-*-* 12:00:00
Unit=regularquery.service

[Install]
WantedBy=multi-user.target
#/etc/systemd/system/regularquery.service
[Unit]
Description="SQL Query

[Service]
Type=oneshot
User=postgres
Environment=PGPASSWORD="mypassword"
ExecStart=/usr/bin/psql -U postgres -d my_database -h localhost -p 5432 -c "INSERT INTO schema.table (name) VALUES ('Insert with a command from terminal');"

試してsudo systemctl start regularquery.service、接続が機能していることを確認してください。モニター出力が利用可能ですjournalctl -u regularquery.service。幸せな時は整理してくださいsudo systemctl enable --now regularquery.timer


または以下でこれを見つけましたman psql

       -w
       --no-password
           Never issue a password prompt. If the server requires password
           authentication and a password is not available from other sources
           such as a .pgpass file, the connection attempt will fail. This
           option can be useful in batch jobs and scripts where no user is
           present to enter a password.

これは、これが~/.pgpass環境変数に対する良い代替手段であることを示唆している。また、--no-passwordプロンプトをインタラクティブに一時停止しないため、ユーザーではなくセッション(crontabやsystemdなど)に適したスイッチであることがわかります。

おすすめ記事