finerss's world!

Crontab 설정

공부/기타2011. 12. 15. 15:43

출처 : http://linuxgazette.net/151/prestia.html

Cronttab(이하 크론탭)은 작업을 일정한 시간에 주기적으로 실행시키기 위해서 사용하는 task 스케쥴링 프로그램이다. 이와 비슷한 프로그램으로 at(1)와 anacron(1)이 있다. at는 원하는 시간에 명령을 한번만실행 시키며, crontab과 같이 주기적으로 실행시키는 기능은 가지고 있지 않다. anacron은 이름에서알 수 있듯이 crontab와 거의 동일하게 사용할 수 있다. 다른점은 시스템 다운이나 anacron 프로그램의 다운 등의 이유로 해당시간에 실행되어야할 프로그램이 실행되지 않았다면, 이를 확인해서 다시 실행시켜준다는 점이다.

다음은 at의 간단한 사용예이다.
# echo "점심시간" | at "12:00"  

joinc는 많은 프로그램들이 주기적으로 돌아간다. 대략 다음과 같은 프로그램들이 주기적으로 작동하고 있다.
  1. 매 5분간격으로 rrd 통계데이터를 생성한다.
  2. 매 5분간격으로 spam 데이터들을 삭제한다.
  3. wiki log 파일을 파싱해서 title에 사용할 색인데이터를 생성한다.
  4. 매 10분 간격으로 cpu 사용율을 측정해서 rrd에 저장한다.
  5. 매 시간주기로 teamblog의 category 정보를 갱신한다.
  6. 매 시간주기로 teamblog에 등록된 블로그RSS정보를 수집한다.
이러한 프로그램들은 특성상 daemon 프로세스로 개발을 해야 할 것인데, 개발하고 관리하기가 보통 까다로운 작업이 아닐 것이란걸 예상할 수 있다. crontab을 사용하면 간단하게 주기적으로 실행하도록 할 수 있다.

crontab는 시스템 프로그램으로 리눅스 배포판에 관계없이 기본적으로 설치가 된다. 크론탭은 내부적으로 자체관리하는 설정파일을 가지고 있는데, 이를 이용해서 크론탭이 사용할 , 에디터 등과 주기적으로 실행할 스크립트를 지정할 수 있다.
[root@localhost ~]# cat /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/  # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly [root@localhost ~]#  

환경변수 영역

첫번째 영역에서는 몇가지 변수를 설정한다.

SHELL
등록된 프로그램을 실행시킬 쉘프로그램을 지정한다. 정의 하지 않을 경우 /bin/sh이 쉘 프로그램으로 지정된다.
PATH
cron은 별도로 쉘을 띄우귀 때문에, 쉘에서 프로그램을 찾기 위한 PATH도 지정해줄 필요가 있다. 왜냐하면 로그인을 해서 shell을 실행시키지 않으므로, 로그인과정에서의 PATH변수를 사용할 수 없기 때문이다.
MAILTO
cron이 수행한 작업의 결과를 mail로 보낼 수 있다. 위의 경우 root유저에게 메일을 전송한다. 만약 MAILTO를 설정하지 않으면 crontab의 실행유저에게 메일이 전송된다.
HOME
cront의 home 디렉토리경로를 설정한다. 기본적으로는 crontab의 실행유저의 홈디렉토리로 /etc/passwd에 설정된 경로를 따른다.

크론탭 포맷

크론탭은 총 6개의 필드로 구성되어 있다. 앞의 5개의 필드가 시간 지정을 위한 필드이고, 마지막 필드에 스케쥴링할 명령어를 지정한다. 아래와 같이 사용한다.
# min             hours        day        month          day      command    34               2           *            *             *       sh /root/backup.sh  
위의 예는 "sh /root/backup.sh"를 매일 2시 34분에 실행한다.

시간은 아래와 같이 5개의 단위로 분류된다.
0-59
0-23
1-31
1-12
주/일 0-6 일요일이 0이다.

별표 (*)는 all을 의미한다.

crontab 설정

크론탭은 유저별로 설정이 가능하다. 해당 유저로 로그인한 다음 "-e"옵션과 함께 crontab을 실행하면 된다. 이때 미리 설정된 에디터가 실행되어서 크론탭 정보를 편집할 수 있는 상태가 된다.
[root@localhost ~]# crontab -e  * * * * * /usr/bin/wall "Hello From Crontab"  
내용을 저장하고 정료하면 다음과 같은 메시지가 출력된다.
crontab: installing new crontab [root@localhost ~]#  
잠시 후, 아래의 메시지가 출력되는 걸 확인할 수 있을 것이다.
Broadcast message from root (Thu Apr  3 14:52:01 2008):  Hello From Crontab  
이 메시지는 매 분마다 출력된다. 왜냐하면 시간 필드의 모든 값을 *로 설정해서, "매월, 매일, 매시간, 매분 마다 실행"하기 때문이다. 어떤 이유로 크론탭을 정지시키고 싶다면 "-r"옵션과 함께 실행하면 된다.
[root@localhost ~]# crontab -r  

Now, say at a certain time in the future you need to start the Apache 'httpd' Web server. We could use a cron job to do this. First, we'll check to see that httpd is not running. Then, we'll do a "date" command to get the current time, so we can set the service to run in the future.

root@localhost ~# service httpd status
httpd is stopped
root@localhost ~#
root@localhost ~# date
Thu Apr 3 15:45:32 MST 2008
root@localhost ~#

We can now easily figure out what 10 minutes from now will be, execute crontab -e in the editor, and write a simple crontab file, remembering the format.

# min(0-59) hours(0-23) day(1-31) month(1-12) dow(0-6) command

55 15 * * * /sbin/service httpd start

For now, just use stars for the day, month, and day of week, and only one space between elements; some distros complain if you have more spaces. So, enter something like this:

55 15 * * * /sbin/service httpd start

root@localhost ~# crontab -e
crontab: Installing new crontab

If you made any mistakes, 'crontab' will tell you about it right as you close the editor. Assuming that everything was right, though, we will have the Apache Web server running less than ten minutes from now. You can use "crontab -l" to list your jobs at any time, to see what is in your crontab and when these jobs are set to run:

root@localhost ~# crontab -l
55 15 * * * /sbin/service httpd start

Yours should look similar. What this means, though, is that 'httpd' is still set to run every single day at the specified time. Again, we'll remove it by executing "crontab -r" to delete all the entries in the file.

root@localhost ~# crontab -r

The combinations seem endless. There are also additional variations for specifying time: "20-27" specifies a range; "3,4,7,8" mean just those intervals for that selection; and */5 would be every 5th interval. Another feature of cron is that, upon completion of a job, it will mail the command output to the user who set up the cron job unless that feature is disabled.
Some more samples

This crontab entry would run the command every 15 and 30 minutes after every hour, during the month of May:

15,30 * * 5 * /usr/bin/command

To run a backup script on just Sundays, Mondays, and Tuesdays at 2:12 AM, the entry would be:

12 2 * * 0-2 sh /root/backup.sh

To run a script at 12 minutes after every 3rd hour of every day, the entry would look like this:

12 */3 * * * sh /root/script.sh

To get cron to write the output of the commands to a log, you can append something like this to the command entry:

12 */3 * * * sh /root/script.sh >> /root/script.log 2>&1

To have cron suppress the e-mail:

12 */3 * * * sh /root/script.sh > /dev/null 2>&1

This is a sample of cron output that would end up in the mail

From root@localhost.localdomain Thu Apr 3 12:08:01 2008
Date: Thu, 3 Apr 2008 12:08:01 -0700
From: root@localhost.localdomain (Cron Daemon)
To: root@localhost.localdomain
Subject: Cron <root@localhost> sh /root/s.sh
Content-Type: text/plain; charset=UTF-8
Auto-Submitted: auto-generated
X-Cron-Env:<SHELL=/bin/sh>
X-Cron-Env:<HOME=/root>
X-Cron-Env:<PATH=/usr/bin:/bin>
X-Cron-Env:<LOGNAME=root>
X-Cron-Env:<USER=root>

test

Some tips for using cron:

  • Always use absolute paths.
  • If you're not sure your cron job completed, check your mail.
  • Remove unneeded cron entries from old cron jobs.
  • Make sure 'crond' is running.

Commands:

crontab -e - Edits the current crontab, or creates a new one.
crontab -l - Lists the contents of the crontab file.
crontab -r - Removes the crontab file.
crontab -u - Edits user's crontab.



/////

RONtab

/etc/cron, /usr/spool/cron/crontabs/*

/etc/cron" 프로그램 주기적으로 어떤 프로그램을 수행시키는데 사용된다.

이때 주기적으로 수행되어질 프로그램은 "/usr/spool/cron/crontabs" 디렉토리

밑에 사용자의 사용자명과 같은 이름으로 생성된다.

화일은 만드는 방법은 아래 명령을 사용하면 된다.

% crontab -l root : /var/spool/cron/crontabs/root 내용 display

% crontab -e root :

명령을 root 수행했으면 /var/spool/cron/crontabs/ DIR 하위에

"root" 라는 이름의 화일이 생성된다)

또는 vi 편집

--------------------------------------------------------------------------------

)

# more /var/spool/cron/crontabs/root

# minute hour day month week

# 0~59 0~23 1~31 1~12 0~6 (0=sunday, 1=monday)

#

15,45 3 * * * find / -name .nfs\* -mtime +7 -exec rm -f {} \; -o -fstype nfs -prune

5 9 * * 6 /usr/lib/newsyslog >/dev/null 2>&1

15 0,8 16 * * find /var/preserve/ -mtime +7 -a -exec rm -f {} \;

--------------------------------------------------------------------------------

crontab 화일의 앞의 5번째 칼럼까지에는 명령이 수행되어질 일시와 요일이다.

지정한 것들은 아래와 같은 의미를 갖는다.

시간 날짜 요일 : 구분은 Space

15,45 3 * * * : 매일 3 15분관 45분에 수행

5 9 * * 6 : 매주 금요일 9 5분에 수행

15 1,18 16 * * : 매달 16 115분과 오후 6 15분에 수행

1) /var/spool/cron/crontabs/root (root계정으로 가정할때..)

파일을 편집하여 원하는 스케쥴을 설정/편집 한다.

2) ps -ef|grep cron : 현재 cron deamon 돌고 있는지 확인

3) kill -9 "pid of cron" : cron deamon kill

4) rm /usr/lib/cron/FIFO : lock파일제거(/usr/lib/cron directory /etc/cron.d 링크되어있음)

5) /usr/sbin/cron : deamon 재실행( 편집한 명령대로 수행함)

) vi /var/spool/cron/crontabs/root

###############################

#Min Hour Day Month Day Command

###############################

15 4 * * * find /var/preserve/ -mtime +7 -a -exec rm -f {} \;

0 23 * * * sh `sed -n 1p /etc/Alis`/janitor

0 * * * * /usr/lib/acct/ckpacct

10 12 * * 1-6 /usr/lib/acct/dodisk

20 12 1 * * /usr/lib/acct/monacct

30 12 * * 1-6 /usr/lib/acct/runacct 2> /var/adm/acct/nite/fd2log

log /var/cron/..... 생성됨

------------------------------------------------------------------------------------

1. 개요 (cron이 뭐하는 것인지 전혀 모르는 분들만)

cron(크론)은 원하는 시간에 명령(프로그램)을 시키기 위한 데몬이다.
서버는 늘 깨어있다는 것을 이용한 최대한의 활용법이 될 수 있다.

- 내가 새벽 3시에 서버에 특정 작업을 해줘야하는데 그 때 깨어있을 수 있는가?
- 또는 30분간격으로 HDD의 사용량을 운영자에게 알리도록 해야한다면?
- 매월 초에 자료를 백업 받고 싶다면?

바로 이럴 때 cron은 최고의 해결책을 제시한다.
cron은 항상 지정한 시간이 되었는지 확인을 하여 해당 명령어을 실행하는 것이다.

2. cron 설정

1) crontab 파일 위치 및 조회

작업 설정 파일을 crontab 파일이라고 부르며, 이 파일의 위치는 OS별로 차이가 있다.
리눅스는 /var/spool/cron/ID, 솔라리스는 /var/spool/corn/crontabs/ID 에 위치한다.
그럼 이 파일을 직접 수정해야 하는가? 그렇지 않다. crontab 명령을 통해 설정과 조회를 한다.

설정 내용을 조회해 보자. (-l 옵션)


$ crontab -l
no crontab for truefeel


설정한 적이 없어 아직 비어있다.

2) crontab 파일 형식


------ -------- ---------------------------------------------------
필 드 의 미 범 위
------ -------- ---------------------------------------------------
첫번째 분 0-59
두번째 시 0-23
세번째 일 0-31
네번째 월 1-12
다섯번째 요일 0-7 (0 또는 7=일요일, 1=월, 2=화,...)
여섯번째 명령어 실행할 명령을 한줄로 쓴다.
------ -------- ---------------------------------------------------


- 한 줄당 하나의 명령 (두줄로 나눠서 표시할 수 없음)
- # 으로 시작하는 줄은 실행하지 않는다.

설정을 해보자. (-e 옵션)
crontab -e 을 하면 vi 에디터가 나온다.(환경변수 EDITOR에 따라 다른 에디터를 사용할 수 있다.)

$ crontab -e
# /home 디렉토리를 /BACKUP/home 으로 백업해둠
#
# 30분, 새벽 4시와 낮 12시, 모든 일, 모든 월, 모든 요일
30 4,12 * * * /usr/bin/rsync -avxH --delete /home /BACKUP/home > /dev/null 2>&1
#
# 파일/디렉토리 퍼미션 설정
# 40분, 새벽 1시, 매주 일요일
40 1 * * 0 /root/bin/perm_set.sh > /dev/null 2>&1



위는 매일 4:30분과 12:30분에 rsync 명령을, 매주 일요일 1:40분에 perm_set.sh를 실행함을 의미한다.

vi 에디터를 통해 설정을 하므로 중요한 몇 가지 에디터 사용법은 익혀야 한다.

---- -----------------------------------------------------------------------------
키 의미
---- -----------------------------------------------------------------------------
i 현재 칸에 글을 넣는다.
o 다음줄에 글을 넣는다.
dd 한줄을 삭제한다.
:wq 저장하고 빠져나온다.
ESC 설정중에 명령어 모드(위의 i, o, dd 등을 사용할 수 있는 상태)로 빠져 나온다.
---- -----------------------------------------------------------------------------


3) 설정 예

시간 설정에서 몇가지 의미있는 것들을 알아보자.

- '*'표시는 해당 필드의 모든 시간을 의미한다.
- 3,5,7 와 같이 콤마(,)로 구분하여 여러 시간대를 지정할 수 있다.
- 2-10와 같이 하이픈(-)으로 시간 범위도 지정할 수 있다.
- 2-10/3와 같이 하이픈(-)으로 시간 범위를 슬래쉬(/)로 시간 간격을 지정할 수 있다.
(2~10까지 3간격으로. 즉, 3,6,9를 의미함)



원하는 시간 형 식
매주 토요일 새벽 2:20 20 2 * * 6 명령어
매일 오후 4,5,6시 0 4-6 * * * 명령어
매일 2시간간격으로 5분대에 5 */2 * * * 명령어
매월 1일 새벽 1:15 15 1 1 * * 명령어
1,7월 1일 새벽 0:30 30 0 1 1,7 * 명령어


3. FAQ

1) cron 설정한 후에는 crond 데몬을 재실행해야 하나요?

아닙니다. crontab -e 으로 설정 후 빠져나오면 바로 적용됩니다.

2) truefeel 사용자는 cron을 못 쓰게 하고 싶습니다.

/etc/cron.allow : 허용할 사용자 ID 목록
/etc/cron.deny : 거부할 사용자 ID 목록

cron.allow 파일이 있으면 이 파일에 들어있는 ID만 사용 가능
cron.deny 파일이 있으면 이 파일에 들어있는 ID는 사용 불가

따라서 cron.deny에 truefeel ID를 추가해주면 됩니다.

3) > /dev/null 2>&1 이 무슨 뜻입니까?

지정한 명령어 처리 결과와 발생할지 모르는 에러메시지를 출력하지 않고 모두 버린다는(/dev/null)는
뜻입니다. 만약 결과와 에러를 파일로 저장하려면 /dev/null 대신 파일명을 적어주면 됩니다.

'공부 > 기타' 카테고리의 다른 글

이클립스 단축키  (0) 2012.01.27
토드 단축키  (0) 2012.01.04
L4 로드밸런싱  (3) 2011.11.08
조인쿼리 정리  (0) 2011.06.13
OpenAPI OAuth  (0) 2011.06.13