본문 바로가기

OS

리눅스 공부하기-06{2023년05월08일}

Crontab(반복 예약 작업)

일정 시간마다 실행될 커맨드나 스크립트를 정의할 수 있어서, 자동적으로 실행될 작업을 관리할 수 있도록 도와준다.

일반적으로 백업, 로그 삭제, 서버 데이터 정리 등 반복적인 작업을 자동화할때 사용한다.

크론탭 설치

[root@localhost ~]# yum install crontab

크론탭 작성

[root@localhost ~]# crontab -e

크론탭 재시작

[root@localhost home]# systemctl restart crond.service

크론탭 작성 후에는 재시작을 해야 적용이 된다.

 

크론탭 작업 리스트 확인

[root@localhost ~]# crontab -l
no crontab for root

크론탭 작업 삭제

[root@localhost home]# crontab -r
* * * * * command
| | | | | <------ Week 0-7 / Sunday = both 0 and 7
| | | |   <------ Month 1-12
| | |     <------ Day 1-31
| |       <------ Hour 0-23
|         <------ Minute 0-59

# 예시-1
30 11 * * 1-5 /usr/bin/find
# 매주 월요일부터 금요일까지 오전 11시 30분에 /usr/bin/find를 실행

# 예시-2
30 */3 * * 1 /usr/bin/find
# 매주 월요일에 3시간 30분마다 실행

30 1 */1

예시

## ls -all을 통해 확인하는 습관을 기르자.

1. 디렉토리인지 파일형식인지 확인하기

2. rwx유무에 대해 확인하기

3. 계정확인하기

4. 계정그룹확인하기

[root@localhost ~]# vi test.sh
[root@localhost ~]# cat test.sh
echo "test"
# test라는 문장이 들어간 sh파일 생성

[root@localhost ~]# ls -all test.sh
-rw-r--r-- 1 root root 12 May  8 15:28 test.sh
# 현재 test.sh는 644이므로 읽고 쓰기는 가능하나 실행 권한이 없음.
# 그렇기에 출력이 안됨

[root@localhost ~]# chmod 744 test.sh
# 현재 계정에게 실행 권한 제공

[root@localhost ~]# ls -all test.sh
-rwxr--r-- 1 root root 12 May  8 15:28 test.sh
# 744

[root@localhost ~]# touch test.tmp
# mkdir은 디렉터리 생성 파일 생성은 touch

[root@localhost ~]# crontab -e
no crontab for root - using an empty one
crontab: installing new crontab
[root@localhost ~]# crontab -l
* * * * * /root/test.sh >> /root/test.tmp
# 1분마다 test.sh를 test.tmp에 실행한다.

[root@localhost ~]# systemctl restart crond.service
# crontab 재시작
[root@localhost ~]# systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2023-05-08 15:30:59 KST; 9s ago
 Main PID: 3056 (crond)
   CGroup: /system.slice/crond.service
           └─3056 /usr/sbin/crond -n

May 08 15:30:59 localhost.localdomain systemd[1]: Stopped Command Scheduler.
May 08 15:30:59 localhost.localdomain systemd[1]: Started Command Scheduler.
May 08 15:30:59 localhost.localdomain crond[3056]: (CRON) INFO (RANDOM_DELA...
May 08 15:30:59 localhost.localdomain crond[3056]: (CRON) INFO (running wit...
May 08 15:30:59 localhost.localdomain crond[3056]: (CRON) INFO (@reboot job...
Hint: Some lines were ellipsized, use -l to show in full.
# crontab status 하기

# 1분마다 생성되는지 확인하기
[root@localhost ~]# cat test.tmp
test
test