운영체제 OS/리눅스 Linux

Q. cron이란? ubuntu에서 crontab 사용법은?

Tap to restart 2022. 8. 5. 23:00
반응형

A. 우분투 문서에 나온 cron 설명을 번역하면 cron은 "백그라운드에서 지정된 시간에 원하는 작업을 실행하기 위해 사용되는 시스템 데몬"을 뜻한다.

 

"Cron is a system daemon used to execute desired tasks (in the background) at designated times."  (출처: CronHowto - Ubuntu documentaion)

 

언제 사용하는가?

크론은 백그라운드에서 특정 시간에 반복 작업이 필요할 때 쓴다. 예를 들어서 서비스를 운영할 때 일별, 월별로 데이터를 집계해서 데이터베이스에 저장할 필요가 있다. 이때 크론을 쓸 수 있다. 한국 시간 기준 서비스를 운영한다면, 새벽 1시에 전날 데이터를 집계하는 식이다. 또는 간단한 날씨앱 같은 경우 정기적으로 데이터 수집이 필요할 것이다. 3시간 단위로 데이터 수집을 하는 것처럼 반복적인 업무를 백그라운드에서 자동으로 돌리고 싶을 때 많이 쓴다. 

 

사용법은?

우분투 기준으로 설명해보겠다. 

 

우선 ec2에 접속하자. 

 

우분투에 python3 명령어를 실행해보자. 이미 python3가 설치되어 있다면 아래처럼 실행된다. 

$ python3
Python 3.8.10 (default, Jun 22 2022, 20:18:18) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

 

vi 명령어로 간단히 파이썬 코드를 하나 짜자.

$ vi hello_world.py

i를 누르면 입력할 수 있다. 

import datetime
now = datetime.datetime.now()
print(f'{now}: Hello World!')

 

다 적은 뒤 esc 키를 누르고 :wq를 누르면 저장하고 나올 수 있다. 그냥 나오고 싶다면 esc 키를 누르고 :q!를 누르면 된다.

준비가 다 되었다. 

 

pwd를 치면 현재 작업 디렉터리 위치가 나온다.

$ pwd
/home/ubuntu

 

crontab -e 명령어를 실행하자. 제일 수정이 쉬운 nano를 고르자.

$ crontab -e

 

크론탭 설명이 나온다. 

 

# 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

위 설명으로는 잘 이해가 안 간다. 

공식 문서를 보자. 

Crontab Lines
Each line has five time-and-date fields, followed by a command, followed by a newline character ('\n'). The fields are separated by spaces. The five time-and-date fields cannot contain spaces. The five time-and-date fields are as follows: minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday).

01 04 1 1 1 /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 4:01am on January 1st plus every Monday in January.

An asterisk (*) can be used so that every instance (every hour, every weekday, every month, etc.) of a time period is used.


01 04 * * * /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 4:01am on every day of every month.

 

분(0~59) 시(0~23) 일(1-31) 월(1-12) 요일(0~6) 순서다.

 

크론 추가

* * * * * python3 /home/ubuntu/hello_world.py >> /home/ubuntu/log.txt

 

이렇게 적으면 매 분마다 hello_world.py가 실행되고 그 결과가 log.txt에 저장된다. 

>>로 하면 계속 누적되고, >만 하면 매번 새로 저장된다. 

 

아래 명령어로 cron을 재시작하자.

$ sudo service cron restart

 

실제 저장이 될까? 

 

1분 지나서보면 log.txt가 생긴 것을 볼 수 있다!

Hello World!가 1분마다 저장된 것을 볼 수 있다.

 

날마다 새벽 1시에 실행하고 싶다면? 아래처럼 입력하면 된다.

0분 1시 *매일 *매월 *모든 요일 순이다.

0 1 * * * python3 /home/ubuntu/hello_world.py >> /home/ubuntu/log.txt

 

매월 1일 0시 0분에 실행하고 싶다면? 아래처럼 입력하면 된다.

0분 0시 1일 *매월 *요일 관계 없이 순이다.

0 0 1 * * python3 /home/ubuntu/hello_world.py >> /home/ubuntu/log.txt
반응형