linux

crontab 설정하기

끼발자 2021. 7. 19. 15:51
반응형

linux상에서 작업하다보면

특정 시간에 반복적으로 수행해야할 일들이 있다.

 

내 경우에 매일 자정에 실행되는 파이썬 파일이 있는데,

multiprocessing 으로 처리하면, 자꾸 connection error가 발생해

아예 cron으로 따로 실행시킨다.

 

사담은 여기까지하고

 

크론탭 설정은 다음과같이 진행하면 된다.

 

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)

 친절하게 "영어로" 적혀있다.

 

크론탭은 

* * * * * script 형식으로 작성하면 된다.

 

앞의 5개의 *는 시간으로 여기에 원하는 시간 간격을 설정한다.

저렇게 크론탭에 넣고 설정하면 매 분마다 file이 실행된다.

처음에 크론탭 확인한다고 저렇게 넣고 실행시켰더니 사양이 낮은 ec2가 다운된 기억이 있다. 조심하자.

 

순서대로 표기하면

분 시간 일 월 요일 이다. 예를 들어

30 00 * * * 이렇게 쓰게되면 매일 00시 30분에 파일이 실행된다.

 

내 경우에는 

30 0 * * * /usr/bin/python3 /home/ubuntu/python_file >> LOGPATH/logs_`date "+\%Y\%m\%d"`.log 2>%1

으로 매일 00시 30분에 파이썬 스크립트가 실행되고, 해당 로그를 저장하도록 작성했다.

 

파이썬 스크립트가 실행되는동안 생성되는 로그를 LOGPATH폴더 안에 logs_%Y%m%d.log 이름으로 저장한다.

작성일자 기준으로 logs_20210719.log

 

2>%1  :  정상출력, 에러출력을 모두 저장한다는데 잘 모르겠다.

>> : 추가. append or +a 정도로 이해하면 된다.

 

물론 파이썬 스크립트가 아니어도 된다.

다음은 직접 짠 쉘파일을 크론에 적용한 예시이다. 매월 1일 08시 00분에 실행하도록 설정했다.

0 8 1 * * /home/ubuntu/clean_log.sh

 

현재 작성되어있는 크론을 확인하려면 

crontab -l 명령어를 사용하면 확인 할 수 있다.

반응형