CronJobs คืออะไร

มันก็คือการทำงานแบบตั้งเวลาการทำงานซึ่งก็เหมือนกับ Batch ละครับ เป็นงานที่ต้องทำตามเวลาทุกวัน หรือทุกเดือนเป็นต้น เรามารู้หลักการทำงานกันนะครับ

ตรวจสอบการทำงานโปรเซสของ Crontab

$ crontab -e

ตรวจสอบว่ามีเปล่า ถ้ายังไม่มีลักษณะข้อมูลตามด้านล่าง ก็จัดการทำตามวิธีดังนี้

1 2 3 4 5 /root/backup.sh or /path/to/command
1: Minute (0-59)
2: Hours (0-23)
3: Day (0-31)
4: Month (0-12 [12 == December])
5: Day of the week(0-7 [7 or 0 == Sunday])
/path/to/command    #Script or command name to schedule.

Easy to remember format :

*  *  *  *  * command to be executed or path to command/script
–  –  –  –  –
|  |  |  |  |
|  |  |  |   —-  Day of week (0 – 7) (Sunday=0 or 7)    #วัน
|  |  |   ——-  Month (1 – 12)                                    #เดือน
|  |   ———-  Day of month (1 – 31)                         #ระบุวันที่
|   ————-  Hour (0 – 23)                                     #ระบุเวลาเป็นชั่วโมง
—————-  Minute (0 – 59)                                   #ระบุเวลาเป็นนาที

ตัวอย่างครับ

To Install or Schedule cron job :

 # In shell prompt type the below command :

$ crontab -e

# Add an below entry to schedule cron job to run at 3:00 PM daily.

* 3 * * * /root/job.sh

save and close the file.
# To get the cronjob output to file add an extra below entry to above command in crontab file which gives the executed cronjob output details to job_log file or else mention your own required path.

* 3 * * * /root/job.sh>/logs/job_log

save and close the file.
# To run the above job at the background even when the user is not logged append the below command to crontab file.

* 3 * * * /root/job.sh>/logs/job_log &

Note :  ampersand (&) helps to run the cronjob in background even when the user is not logged in.
# To run or install cronjob for specific user add username to the above command before giving the path to the script or command.

* 3 * * * username /root/job.sh

or

* 3 * * * username /root/job.sh>/logs/job_log

or

* 3 * * * username /root/job.sh>/logs/job_log &

To List all your crontab jobs:-

$ crontab -l 

To List specific user crontab jobs:

 

$ crontab -u username -l

To remove all crontab jobs :

$ crontab -r

To remove specific user crontab jobs:

$ crontab -r -u username

To Backup all crontab jobs:

$ crontab -l > /backup/cronjob.bakup

To Backup specific user crontab jobs:

$ crontab -u username -l > /backup/username.bakup

Facebook Comments