วันเสาร์ที่ 16 พฤษภาคม พ.ศ. 2563

[Ubuntu] การติดตั้ง และ การใช้งาน Cron Jobs

การติดตั้ง Cron ก่อนอื่นให้เราเช็คดูก่อนว่ามีการติดตั้งลงไปที่เครื่องแล้วหรือยัง
dpkg -l cron

# cron installed

Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version               Architecture    Description
+++-===============-====================-===============-==============================
ii  cron            3.0pl1-128.1ubuntu1  amd64           process scheduling daemon


เมื่อพบว่ายังไม่ได้ทำการติดตั้งให้เราทำการ Update Package ก่อนทำการติดตั้ง และเมื่อทำการติดตั้งแล้วให้เช็คว่า Cron ทำงาน
apt update
apt install cron

systemctl status cron




การเข้าไปแก้ไขข้อมูลใน Cron Jobs ให้เราทำการแก้ไขที่ไฟล์ /etc/crontab สามารถใช้คำสั่ง nano /etc/crontab ได้เลย เมื่อทำการเปิดไฟล์ขึ้นมาแล้วจะพบข้อมูลประมาณนี้ก่อน
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#

โดยข้อมูล 5 ตัวแรกจะเรียงแบบนี้
* * * * *

ความหมายของแต่ละตัวคือ
1. หมายถึง นาที (minute) สามารถระบุได้ตั้งแต่ 0 - 59
2. หมายถึง ชั่วโมง (hour) สามารถระบุได้ตั้งแต่ 0 - 23 (0 = midnight)
3. หมายถึง วันที่ (day) สามารถระบุได้ตั้งแต่ 1 - 31
4. หมายถึง เดือน (month) สามารถรถบุได้ตั้งแต่ 1 - 12
5. หมายถึง วันในสัปดาห์ (weekday) สามารรถระบุได้ตั้งแต่ 0 - 6 (0 = Sunday)

ในเว็บของ https://www.geeksforgeeks.org/ ได้ให้ตัวอย่างไว้ 2 อัน

ตัวอย่างที่ 1
ใช้คำสั่ง crontab -e เพื่อทำการเพิ่ม cron job สั่งให้ทำงาน script backup-script.sh ในวันแรกของทุกเดือนตอนเวลา 9 โมง
#crontab -e //install your cron job by running this command.
// Append the following entry.

0 9 1 * * /path/to/script/backup-script.sh

ตัวอย่างที่ 2
ใช้คำสั่ง crontab -e เพื่อทำการเพิ่ม cron job สั่งให้ทำงานทุกวันเวลา 10 โมง
#crontab -e //add cron job

// Append the following entry.
0 10 * * * /path/to/myphpscript.php



การใช้งานคำสั่งอื่น ๆ
# แสดงรายการ cron job
crontab -l

# ลบ cron job ปัจจุบัน
crontab -r

man cron
man crontab



ขอบคุณข้อมูลจาก
https://help.ubuntu.com/community/CronHowto
https://www.geeksforgeeks.org/

ไม่มีความคิดเห็น:

แสดงความคิดเห็น