»
S
I
D
E
B
A
R
«
A simple bash script to schedule tasks
February 9th, 2009 by sayanriju

For some bizzarre reason, I have never been able to run cron successfully on my system. Mostly, I need functionalities like that offered by cron when I schedule my downloads to stop at the end of ‘happy hours’ of BSNL Broadband (2 am to 8 am).
Instead of trying to google up and solve my problem, I just wrote a simple bash script which will address my needs! The job the script does is quite elementary: it takes as argument a time and a command, and runs the command at that scheduled time.

Here’s the script:

#!/usr/bin/env bash

if [ "$#" -ne 2 -o `echo "$1" | awk -F ":" '{print NF}'` -ne 3 -o "$1" == "-h" -o "$1" == "--help" ];then
	## Print uasge instructions
	echo -e "Usage:	 mycron  \n	(Both arguments are mandatory)\nRuns specified command at specified time\n"
	echo -e "Note: You must specify the time for execution EXACTLY as HH:MM:SS\n"
	echo -e " E.g.: 09:00:00 instead of 9:00:00 or 09:00 "
	echo -e "\nAlso, 24 Hour clock format is expected,\nso use 21:00:00 instead of 09:00:00 if you mean PM\n\n"
	echo -e "mycron -h, --help : Display this help message and exit\n"
	exit
fi

while true;do
    ctime=`date | tr -s ' ' | cut -d' ' -f4 `
    if [ "$ctime" == "$1" ];then
	"$2" &
	echo -e "Process $2 with PID $! has been run at $ctime\nAborting script $0"
	exit
    fi
done

Of course, this script can be made to do things a lot better, but right now, it does exactly what I need!


Leave a Reply

»  Substance: WordPress   »  Style: Ahren Ahimsa
© Sayan Chakrabarti (http://sayanriju.co.cc)