티스토리 뷰

Operating System/Ubuntu

01. 스케쥴러

내 꿀은 어디에서 왔을까? 2024. 6. 24. 18:00

우분투에서 스케쥴러인 타이머를 설정하는 방법에는 여러 가지가 있다. 대표적으로는 'cron' 과 'systemd' 타이머를 사용하는 방법이다.

'cron' 은 주기적으로 작업을 실행할 수 있게 해주는 유닉스 기반의 스케쥴러이다.

'systemd'는 현대 리눅스 배표판에서 사용되는 시스템 및 서비스 관리자 이다. 이를 사용하면 더 정교한 타이머 설정이 가능하다고 한다.

 

/lib/systemd/system 하위에 filename.service 파일과 filename.timer 파일을 작성한다.

 

1. filename.service

[Unit]
Description=Run example script

[Service]
ExecStart=/path/to/your/script.sh

2. filename.timer

[Unit]
Description=Run example script every day at 3 PM

[Timer]
OnCalendar=*-*-* 15:00:00

[Install]
WantedBy=timers.target

 

  • OnCalendar를 사용하여 주기를 설정하면 된다.
  • 위의 예시는 매일 오후 3시를 의미
  • OnCalendar=hourly : 매 시간마다
  • OnCalendar=weekly : 매주 
  • 위와 같이 스케쥴러 시간 설정을 하면 된다.

 

3. 타이머 활성화 및 시작

 

sudo systemctl enable example.timer
sudo systemctl start example.timer

 

 

4. 간단한 스케쥴러 업무 요구 사항

  • 현재 스케쥴러는 SSL 인증서 (https 사용)를 Auto renew 하는데, 갱신이되고나면 nginx도 재실행하여 브라우저의 인증서가 갱신이 되어야 한다.
  • 그래서 기존에 .service 파일의 ExecStart=/usr/bin/certbot -q renew  를 스크립트 파일이 실행될 수 있게 한다. 
  • 스크립트는 아래와 같다.
  • 나는 /usr/local/bin 하위에 아래 셀 스크립트 파일을 저장하였다.
  • renew_cert_restart_nginx.sh
#!/bin/bash

# Certbot 명령어를 통해 인증서를 갱신하고, 결과를 로그 파일에 저장합니다.
certbot renew --post-hook "systemctl restart nginx" > /var/log/certbot_renew.log 2>&1

# 로그 파일에서 'No renewals were attempted' 메시지를 확인합니다.
if grep -q "No renewals were attempted" /var/log/certbot_renew.log; then
    echo "인증서 갱신이 시도되지 않았습니다. 아직 1개월 이상의 기간이 남아 있을 수 있습니다."
else
    echo "인증서가 갱신되었으며, nginx 서비스를 재시작했습니다."
fi

 

  • 로그를 파일로 저장해서 로그 메시지를 확인 후 갱신되면 nginx를 재실행한다.
  • --post-hook "systemctl restart nginx의 post-hook 옵션은 인증서 갱신 작업이 완료된 후 실행할 명령어를 지정
  • > /var/log/certbot_renew.log 2>&1 는 출력에 대한 리다이렉션을 /var/log/certbot_renew.log 파일로 저장
  • '>' 는 표준 출력을 to file로 보내는 의미 이고, 2>&1은 표준 오류(에러) 출력을 표준 출력으로 병합하여 동일한 파일에 저장한다는 의미이다.
  • 스크립트를 실행할 수 있도록 권한을 줘야한다.
chmod +x /path/to/renew_cert_restart_nginx.sh

 

그래서 서비스 파일을 아래와 같이 수정

[Unit]
Description=Certbot
Documentation=file:///usr/share/doc/python-certbot-doc/html/index.html
Documentation=https://certbot.eff.org/docs

[Service]
Type=oneshot
ExecStart=/path/to/renew_cert_and_restart_nginx.sh
PrivateTmp=true
  • path/to 부분은 실제 셀 스크립트가 있는 /usr/local/bin 으로 바꿔주면 된다.
  • 작업을 완료하였으면 시스템 타이머 재시작
sudo systemctl daemon-reload
sudo systemctl restart certbot.timer