Running a cronjob with different parameters each day

I am a programmer, and do not know a lot about crons, but I want to know if this is possible.

Lets say I have an array [option1, option2, option3] and a script which I run in NodeJS called script.js. I want to run this script each day at 1 am. The cron command of this would be:

0 1 * * * node ~/script.js

Well now the tricky part, I want to rotate the options each day, so for example monday I want to run node ~/script.js option1, the next day node ~/script.js option2 and so on. Also, I want to be able to add/remove options when needed, but the rotation should stay intact.

Is this possible in any way? I know I could do this within node also, but I'd rather do this from outside the script, and leave the script as it is.


Also, I want to be able to add/remove options when needed, but the rotation should stay intact.

That's tricky. What does it mean for the rotation to stay intact after modification of the list of options? After all, you could be completely rebuilding the list, destroying any clue as to where you were.

What you probably could do is set up a directory with files which represent your options (either via their file name, or their content). Then whenever the cron job executes, you'd list that directory, sorting files by last modification time. You take the oldest entry, touch that file to change its modification time to the current time, then use it to run the script.

#!/bin/bash
cd ~/script-options
next=$(ls -rt | head -n1)
touch -- "${next}"
node ~/script.js ${next} or $(<"${next}")

If you want to, you can write this in a single line for cron as well, though it will become harder to read.

Adding options means adding new files to the options directory. Removing options means deleting files. At any point, the oldest file is the one to be run next, so new options will be added at the very end of the cycle, as if the had just been run. If you want to re-order options, you can touch them in any order you want.


Let's say you want a different option for each day of the week. You can:

  1. Have a separate cron job for these:

    0 1 * * 0 node ~/script.js option1
    0 1 * * 1 node ~/script.js option2
    0 1 * * 2 node ~/script.js option3
    

    etc...

  2. Have bash provide the desired options for you:

    0 1 * * * node ~/script.js case `date +%u` in 0 ) echo option1 ;; 1 ) echo option2 ;; 2 ) echo option3 ;;  esac
    

    (I didn't run the latter, so it might need some tweaking - but that's the general idea.)


No, I can think of no clean way to do this. Just write a simple shell wrapper script that checks the date and starts up your node application with your required options each day.