การใช้ Crontab บน CentOS 7

Supara Dighton-Mason
2 min readApr 3, 2018

--

Crontab คือ Automate system task บน CentOS ซึ่งทำงานอัตโนมัติตามเวลาที่เรากำหนด สามารถใช้ประโยชน์กับงานที่ต้องทำซำ้ๆ ยกตัวอย่างเช่น ต้องการลบ log file บน server ทุกวันเวลาเที่ยงคืน เป็นต้น

การติดตั้ง Crontab

1.Connect ผ่าน SSH และทำการ Update Software เป็นเวอร์ชั่นล่าสุด

sudo yum update

2.ทำการตรวจสอบ และ ติดตั้ง cronie package โดยปกติ cron utility จะถูกติดตั้งมาแล้ว เราสามารถ verify และ confirm ด้วยคำสั่ง

sudo rpm -q cronie

หากยังไม่ได้ ติดตั้ง ให้ใช้คำสั่งดังนี้

sudo yum install cronie

3.ทำการ check ว่า service ทำงานหรือไม่

sudo systemctl status crond.service

กรณีที่ Crontab ทำงานเป็นปกติ จะแสดงผลลัพธ์ Active: active (running)

การใช้งาน Crontab

1.สามารถแก้ไขเปลี่ยนแปลง Crontab ได้ใน /etc/crontab ใช้คำสั่งแสดงสิ่งที่อยู่ในไฟล์

sudo cat /etc/crontab

ภายในจะมีคำอธิบายและการใช้ crontab ดังนี้

SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO="" # For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 5 * * * root run-parts /etc/cron.daily 22 5 * * 0 root run-parts /etc/cron.weekly 42 5 1 * * root run-parts /etc/cron.monthly

2.Option ของ crontab สามารถดูได้ใน Help ซึ่งจะมี Option ที่มีประโยชน์ ต่างๆดังนี้

Usage: crontab [options] file crontab [options] crontab -n [hostname] Options: -u define user -e edit user's crontab -l list user's crontab -r delete user's crontab -i prompt before deleting -n set host in cluster to run users' crontabs -c get host in cluster to run users' crontabs -s selinux context -x enable debugging

ตัวอย่างการใช้งาน Crontab

ตัวอย่าง ให้ทำการลบ log file ที่เก่ากว่า 5 วัน เวลาเที่ยงคืน

1. ใช้คำสั่ง crontab -l เพื่อตรวจสอบ list Crantab ของ User นั้นๆ

crontab -l

2. หากไม่มีให้เพิ่ม crontab job ด้วยคำสั่ง crontab -e

crontab -e

3. เพิ่ม job เช่น

0 * * * * find /yourfile/logs/ -mtime +5 -exec rm {} \;

คำสั่งนี้จะทำการลบ log file ที่เก่ากว่า 5 วัน ในเวลาเที่ยงคืนของทุกๆวัน

4. ทำการ save file
5. Restart crontab ด้วยคำสั่ง

sudo systemctl restart crond.service

หรือใช้คำสั่งเพิ่ม job แบบบรรทัดเดียว โดยไม่ต้องสร้าง script file ซึ่งตัวอย่างนี้จะมีประโยชน์สำหรับ สร้าง job ผ่าน Build&Deployment Framework

(crontab -l ; echo "0 * * * * find /yourfile/logs/ -mtime +5 -exec rm {} \;") | crontab -

จากนั้นทำการ Restart crontab

Challenge : ให้ลองสร้าง script แสดง Text และใช้ crontab ในการ run script ทุกๆ 1 ชั่วโมง

References

View all posts by S.D.Mason

Published April 3, 2018August 2, 2018

Originally published at suparadighton.com on April 3, 2018.

--

--