프로그래밍/예전글

Ubuntu crontab 사용법

Cat체셔 2017. 10. 4. 13:04

참조 : https://help.ubuntu.com/community/CronHowto


Crontab은 특정 시간에 설정해놓은 커맨드를 실행하는 서비스입니다.


특정 시간에 실행할 커맨드를 등록하는 Crontab 파일을 수정할 수 있게 해주는 명령어입니다. 첫 실행 시, 파일 에디터를 선택합니다. 저장하고 마치면 자동으로 Crontab에 install해줍니다.

crontab -e


특정 시간에 root권한으로 실행할 커맨드를 등록하는 Crontab 파일을 수정할 수 있게 해주는 명령어입니다. 위와는 다른 파일이 열립니다. 마찬가지로 저장하고 마치면 자동으로 Crontab에 install해줍니다.

sudo crontab -e


위에서 등록한 Crontab파일을 제거하는 명령어입니다.

crontab -r

sudo crontab -r


크론탭 파일을 열면 아래와 같은 문서가 보입니다.

# 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

해당 문서에 아래와 같은 명령어를 추가해줍니다.

분 시 일 월 요일 /usr/bin/somedirectory/somecommand

분 : 0~59

시 : 0~23 (0 : 자정)

일 : 1~31

월 : 1~12

요일 : 0~6(0 : 일요일)


아래는 예시입니다.

1월 1일 월요일 4시 1분에 /usr/bin/somedirectory/somecommand를 실행하는 Crontab line입니다.

01 04 1 1 1 /usr/bin/somedirectory/somecommand

매일 4시 1분에 /usr/bin/somedirectory/somecommand를 실행하는 Crontab line입니다.

01 04 * * * /usr/bin/somedirectory/somecommand

요일은 상관없이 1월, 6월 1일부터 15일까지 4시, 5시 1분, 31분 마다 /usr/bin/somedirectory/somecommand를 실행하는 Crontab line입니다.

01,31 04,05 1-15 1,6 * /usr/bin/somedirectory/somecommand

매 10분마다(0분, 10분, 20분, 30분, 40분, 50분) /usr/bin/somedirectory/somecommand를 실행하는 Crontab line입니다.

*/10 * * * * /usr/bin/somedirectory/somecommand


아래는 시간 위치에 사용할 수 있는 특수한 문자열입니다.

string

meaning

@reboot

컴퓨터가 실행될 때 실행합니다.

@yearly

매년 1월 1일 0시 0분에 실행합니다.(0 0 1 1 *)

@annually

@yearly와 같습니다.

@monthly

매달 1일 0시 0분에 실행합니다. (0 0 1 * *)

@weekly

매주 일요일 0시 0분에 실행합니다. (0 0 * * 0)

@daily

매일 0시 0분에 실행합니다. (0 0 * * *)

@midnight

@daily와 같습니다.

@hourly

Run once an hour, "0 * * * *".


아래와 같이 사용할 수 있습니다.

@reboot /path/to/execuable1


crontab 로그 확인(logging)

cat /var/log/syslog 를 통해 crontab의 실행 여부를 확인할 수 있습니다.

postfix를 설치(sudo apt-get install postfix)하시면 cat /var/mail/username를 통해 crontab이 남긴 log를 확인하실 수 있습니다.

아니면 아래를 통해 사용자 정의한 위치에 로그를 남기실 수 있습니다.

01 14 * * * /path/to/myscript >> /home/log/myscript.log 2>&1

14시 1분에 /path/to/myscript를 실행한 후, 로그를 /home/log/myscript.log에 저장합니다.
여기서 2>&1은 stderr를 stdout으로 변경한다는 뜻입니다.