캠핑과 개발

linux 환경에서 구동되는 프로그램을 만들었는데 사용자의 요청에 의해서

리눅스가 처음 시작할때 자동으로 프로그램을 실행하도록 요청을 받을때 간단하게 사용합니다.

 

chkconfig 라는 명령으를 통하여 등록을 할 수도 있지만 리눅스의 부팅과정을 이해해야하며

런레벨에 대한 정보도 학습해야 합니다. 리눅스도 잘 모르는 사용자라 하면 복잡하게 느껴질수도 있습니다.

 

하지만 해당 방법은 crontab을 통하여 등록할 수 있으며 사용방법이 간답합니다.

 

사용법

 

1. 프로그램이 실행하고자 하는 계정으로 로그인 한 후 아래 명령어를 입력하여 편집모드로 들어갑니다.

crontab -e 

 

2. @reboot 명령을 통하여 실행하고 하는 명령어를 입력합니다.

예를 들어서 부팅시 어떤 프로그램을 를 자동으로 실행하기 위한 명령어를 등록하기 위해서서 아래와 같이 입력하였습니다.

 

@reboot /home/test/test/programstart.sh 

 

3. 저장한 후 vi를 닫습니다.

 

crontab은 일반적으로 사용하는것 외에 특정 몇가지 활성화 매계변수가 존재하는데 아래와 같은 것들이 있습니다.

직접 쳐도 되지만 간단하게 사용할 수도 있으니 유용하게 사용되었으면 합니다. 

@reboot = run at boot and reboot only

@yearly  = run at midnight Jan 1 each year (equiv to 0 0 1 1 *)
@annually  = run at midnight Jan 1 each year (equiv to 0 0 1 1 *)
@monthly  = run at midnight on the first day of each month (equiv to 0 0 1 * *)
@weekly  = run at midnight each Sunday (equiv to 0 0 * * 0)
@daily  = run at midnight each day (equiv to 0 0 * * *)
@ midnight  = run at midnight each day (equiv to 0 0 * * *)

@ hourly = run on the first second of every hour (equiv to 0 * * * *) 

crontab format:
{activation parameters} {command #1} ; {optional command #2} ; {optional command #3} ; {etc, commands end on the line ending}

Example:
* * * * * ./folding
This would cause folding to be launched every minute, from your home folder. Very bad, you would end up with 60 copies running by the end of an hour.

Commands are shell commands. Separate multiple commands with a semicolon ";" and end on the line ending.

Activation parameters:
@reboot = run at boot and reboot only
@yearly = run at midnight Jan 1 each year (equiv to 0 0 1 1 *)
@annually = run at midnight Jan 1 each year (equiv to 0 0 1 1 *)
@monthly = run at midnight on the first day of each month (equiv to 0 0 1 * *)
@weekly = run at midnight each Sunday (equiv to 0 0 * * 0)
@daily = run at midnight each day (equiv to 0 0 * * *)
@ midnight = run at midnight each day (equiv to 0 0 * * *)
@ hourly = run on the first second of every hour (equiv to 0 * * * *)
- or -
1 2 3 4 5 = specific time tags
- where -
1 = Minute (of hour) to activate [0-59]
2 = Hour (of day) to activate [0-23]
3 = Day (of month) to activate [1-31 ... 29,30,31 may not activate during all months]
4 = Month (of year) to activate [1-12 or 3-letter names "Jan,Feb,Mar"]
5 = Weekday to activate [0-7 or 3-letter names "Mon,Tue,Wed"]

If 3-letter names are used on Month/Weekday instead of numbers, they are case-insensitive. "Mon" and "mON" are equally acceptable. If numbers are used for the weekday, "0" and "7" are both Sunday and are interchangeable.

Time tags are separated by spaces. Do not use spaces within a tag, this will confuse cron. All five tags must be present. They are a logical AND of each other. There is another space between the last time tag and the first command.

A time tag can be a wildcard "*", which means "all". It can be one value, several values, a range, or a fractional range.

Examples for the Hour column:
8 = one value: execute in the 8 AM hour
5,6,9 = multiple values: execute in the 5, 6, and 9 AM hours
5-8 = range: execute in each hour between 5-8 AM (inclusive)
*/2 = fractional: execute in every other hour. 0 (midnight), 2AM, 4AM, 6AM, etc
3-12/3 = fractional range: execute in every third hour between 3AM and 12PM: 3AM, 6AM, 9AM, 12PM

Example:
5 */3 * * 1-5 cd "desktop/fold1"; ./fold &
This will launch on the 5-minute mark, every third hour, every day, every month, but only on days of the work week (Mon-Fri). It cd's to the Desktop/Folding folder #1, then launches the launch script in nohup mode so folding will keep running.

1. 개요

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



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 대신 파일명을 적어주면 됩니다.





'DEVELOPMENT > Linux' 카테고리의 다른 글

rpm 명령어 사용하기  (0) 2012.05.17
linux 명령어 - yum  (0) 2012.05.17
linux shell 스크립트  (0) 2012.01.13
Fedora 16 | systemctl - 서비스 관리 명령어  (0) 2011.12.01
linux mysql 바이너리 버전 설치  (0) 2011.11.29