Tuesday, August 4, 2015

How to schedule cron jobs on an ASUS wireless router

Want to run a task on a regular schedule on your ASUS wireless router? Well, you're out of luck.

Or are you?

Cron is the well-known method of scheduling tasks for Unix, the equivalent of "at" on Windows. My purpose is not to document the use of cron - it is well documented elsewhere. Alas, ASUS does not include the crontab utility for creating and editing jobs in its firmware, but the cron daemon (crond) is installed and running. If a jobs file can be loaded into the daemon, crond will happily run the jobs.

A lesser documented standard feature in crond is to watch the directory /var/spool/cron/crontabs/ for a file listing jobs to run. Ordinarily you should not modify files in this directory manually - that's what crontab is for - but absent crontab one can still manually edit a file and place it in this folder.

For instance, if I create a file with the following contents, and copy it to /var/spool/cron/crontabs/<admin user name>, it will run the job.sh script every 5 minutes:
# cron jobs to import into root's crontab
*/5 * * * * /jffs/job.sh
Simple and sweet.

A minor "gotcha" is that /var is volatile storage; it is wiped out and recreated every time the router boots, so any cron file placed in that directory has to be replaced upon reboot.

One undocumented feature in ASUSWRT is the ability to specify a custom script to execute anytime a USB drive is mounted. Since a USB drive that is plugged into the router has to be mounted before use, this feature also has the effect of substituting for a "run at boot" script, as long as there is a USB drive attached.


ASUSWRT also provides a small portion of persistent storage useful for placing files that you don't want to be deleted upon rebooting. This folder is located at /jffs, and is a convenient place to store custom scripts. Just be aware that while /jffs is not disturbed by rebooting, it might be deleted upon installing an updated firmware. I keep a backup copy of my custom scripts elsewhere, but for simplicity sake I run them from /jffs.

The syntax to cause a script to run upon mounting a USB drive is:

nvram set script_usbmount="/jffs/scriptname"
nvram commit
For our purposes, /jffs/scriptname contains the following line to copy a cron file from persistent storage into the folder watched by crond:
cp /jffs/<admin user name> /var/spool/cron/crontabs
Make sure the file permissions allow executing (running) the script; since this is Unix, the simplest way to do this is chmod 755 scriptname. Incidentally, there is also a script_usbumount option that runs upon unmounting or removing a USB drive. If you are so inclined, run nvram show to see a very long list of parameters ASUSWRT stores.

Why might one want to schedule tasks on a router? Here are a few examples: