[Linux] Cron, Crond, Crontab 이란?

ASHAPPYASIKNOW·2022년 7월 25일
0

OS(Linux, Mac, Windows)

목록 보기
4/9
post-thumbnail

Cron, Crond, Crontab

Cron

일반적으로 스케줄 서비스의 이름이다.

Crond

crond 은 cron daemon을 의미한다. 실제로 crontab에서 작업을 읽어서 실행하는 daemon이다. 그러므로 crontab이 변화가 생기면 crond를 재시작해 주어야 한다.

Crontab

crontab은 실행주기 혹은 실행시간이 지정된 작업의 모음이다.


Crontab 설치 및 사용 방법

cron 확인

sudo systemctl list-unit-files | grep crond

> sudo systemctl list-unit-files | grep crond
crond.service  enabled

설치

sudo yum update -y
sudo yum install -y cronie

참고: -y, --assumeyes: answer yes for all questions (모든 대답에 yes를 기본으로 설정)

기본 명령어

Crontab list 확인

crontab -l

Crontab 스케줄 등록

crontab -e

Crontab 삭제

crontab -r

Crond 시작

sudo systemctl start crond

Crond 재시작

sudo systemctl restart crond

Crond 활성화

sudo systemctl enable crond

Crontab 작업 규칙

  *   *   *  *   * (명령어)
[분, 시, 일, 월, 년] ~/rsync.sh

ex) 1분마다 rsync.sh 파일 실행

* * * * * ~/rsync.sh

ex) 12시간마다 rsync.sh 파일 실행

* */12 * * * ~/rsync.sh

ex) 새벽 4시마다 rsync.sh 파일 실행

0 4 * * * ~/rsync.sh

ex) 새벽 4시부터 1분마다 rsync.sh 파일 실행

* 4 * * * ~/rsync.sh

사용예제

rsync를 이용해서 1분마다 파일을 복사하는 예제

crontab 작업등록기 실행

> crontab -e

crontab -e

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

* * * * * /home/ec2-user/rsync_scripts/rsync_logs
#!/bin/bash

nowdate=$(date "+%Y-%m-%d %H:%M:%S")
echo "Today is ${nowdate}, cron daemon execution complete." >> /home/ec2-user/rsync_scripts/crond_execution.log

echo 'rsync logs ...'
rsync -avzh /srv/my-server/logs/ /efs-my-folder/logs/

1분마다 rsync_logs.sh
저장한 후 재 반영과정이 필요하다.

crontab 작업 재 반영

sudo systemctl restart crond


동작 및 문제발생 확인

crond가 동작할 아래와 같은 내용을 확인 할 수 있다.

vim /var/spool/mail/ec2-user

오류 내용 및 실제 동작내역도 확인할 수 있다.

sudo chmod +x ~/rsync_scripts/rsync_logs.sh

파일에 실행권한을 추가해 주면 해결된다.


REFERENCES

Difference between Cron and Crontab?

profile
36.9 It's good time to start something new

0개의 댓글