How to set a crontab to run command on the last day of every month.

crontab scheduleเป็นที่ทราบกันดีว่าใน crontab ของ linux มีแค่การกำหนด เวลา วัน เดือน ในการทำงานเท่านั้น หากว่าจะต้องการให้ทำงานในวันสุดท้ายของเดือน หรือ เสาร์แรกของเดือน จะไม่สามารถทำได้ แต่ถ้าหากรู้วิธีการเขียน script ก็สามารถใช้ script มาช่วยในการควบคุมการทำงานอีกต่อหนึ่งได้ ซึ่งในบทความนี้ผมได้นำตัวอย่าง script ที่ใช้ร่วมกับ crontab เพื่อให้สามารถกำหนดวันการทำงานได้อย่างถูกต้องตามความต้องการมากขึ้น

ตัวอย่าง script ที่จะให้ทำงานในวันสุดท้ายของเดือน

สร้างไฟล์ lastdaymonth.sh

[shell][root@Ezylinux ~]# vi /root/lastdaymonth.sh[/shell]

[shell]
#!/bin/bash

TODAY=`/bin/date +%d`
TOMORROW=`/bin/date +%d -d "1 day"`

# See if tomorrow’s day is less than today’s
if [ $TOMORROW -lt $TODAY ]; then
COMMAND //ใส่คำสั่งที่ต้องการให้ทำงาน
fi
exit 1
[/shell]

สร้าง schedule การทำงาน

[shell][root@Ezylinux ~]# crontab -e[/shell]

[shell]
1 0 * * * /root/lastdaymonth.sh
[/shell]

ตัวอย่าง script ที่จะให้ทำงานในวันเสาร์แรกของเดือน

สร้างไฟล์ 1stSat.sh
[shell][root@Ezylinux ~]# vi /root/1stSat.sh[/shell]

[shell]
#!/bin/bash

DAY=`date +%d`
if (($DAY <= 7)) ; then
COMMAND //ใส่คำสั่งที่ต้องการให้ทำงาน
fi
exit 1
[/shell]

สร้าง schedule การทำงาน

[shell][root@Ezylinux ~]# crontab -e[/shell]

[shell]1 0 * * 6 /root/1stSat.sh[/shell]

You May Have Missed