![Debian - crontab을 사용하여 SQL 쿼리 예약](https://linux55.com/image/202377/Debian%20-%20crontab%EC%9D%84%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20SQL%20%EC%BF%BC%EB%A6%AC%20%EC%98%88%EC%95%BD.png)
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 구현(데비안과 함께 제공되는 구현 포함)을 사용하면 처음 몇 줄에서 환경 변수를 설정할 수 있습니다.
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');"
크론 작업이어야 합니까? 데비안을 실행하고 있으므로 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)에 대한 좋은 스위치임을 보여줍니다 .