Giuseppe Parrello

 

How to schedule jobs on a router


Introduction

On a Linux operating system, jobs are scheduled using the "cron" service, with this service we can run "cron" jobs.
The "cron" jobs allow Linux users to execute commands or scripts at a specific date/time. For example, we can schedule scripts to run periodically.
The "cron" jobs are one of the most useful tools in Linux. The "cron" service (daemon) runs in background and constantly checks for the presence of "crontab" files within the operating system.


How to manage "cron" jobs

To manage "cron" jobs on a Router (Asus RT-AC86U) we use the "cru" command, this command adds, deletes and lists the "cron" jobs.
The "cru" command is actually a script and simply handles the "crontab" file in the "/var/spool/cron/crontabs" folder - the name of the "crontab" file is actually called "admin" since "admin" is the main user with the highest privileges on a router.


The "cru" command

This is an example of the "cru" script on a router:

#!/bin/sh
D="/var/spool/cron/crontabs"
U="$D/cron.update"
F="$D/`nvram get http_username`"
N="$F.new"
L="/var/lock/cron.lock"

if [ $# -gt 1 -a "$1" = "a" -o "$1" = "d" ]; then
        if [ -f $L ];
        then
                I=$((($$ % 25) + 5))
                while ! rm $L 2>/dev/null; do
                        I=$(($I - 1))
                        [ $I -lt 0 ] && break
                        sleep 1
                done
        fi

        ID=$2
        grep -v "#$ID#\$" $F >$N 2>/dev/null
        if [ "$1" = "a" ]; then
                shift
                shift
                echo "$* #$ID#" >>$N
        fi
        mv $N $F
        echo `nvram get http_username` >>$U

        echo >$L
        exit 0
fi

if [ "$1" = "l" ]; then
        cat $F 2>/dev/null
        exit 0
fi

cat <<END

Cron Utility
add:    cru a <unique id> <"min hour day month week command">
delete: cru d <unique id>
list:   cru l

END
exit 0

Instead this is an example of the help of the "cru" command:

Cron Utility
add: cru a <unique id> <"min hour day month week command">
delete: cru d <unique id>
list: cru l

The first parameter "unique id" contains a unique ID for the "cron" job.
The second parameter of the above-mentioned "cru" command follows the same instructions as the "crontab", so we will have:

Examples of the "cru" command

To run a script every 5 minutes, we will use the "cru" command as follows:

cru a everyfiveminutes "*/5 * * * * sh /opt/etc/myscript.sh"

To run a script at 4:00 am every day:

cru a backupscript " 0 4 * * * sh /opt/etc/myscripts/backup_script.sh"

To run a script at 4:00 am but only on Sundays and Wednesdays:

cru a backupscript " 0 4 * * 0,3 sh /opt/etc/myscripts/backup_script.sh"