Programming, automation, algorithms, macOS, and more.

Run Command Every Other Week

I run a few things via cron, some of them need to run in intervals that cannot be expressed, for example biweekly or every 8th month.

As a general solution I created the every command available here.

The supported usage is:

every [-n number] command [argument ...]

This will run command every number time it’s invoked. For example to send an email the third, sixth, ninth, etc. time we call it, use:

every -n3 mail -s"Water the plants" <<< "It’s time again!"

Using this in a crontab to remind us every second Wednesday could be done as:

#  m  h dom mon dow command
  00 12   *   * wed every -n2 mail -s"Water the plants" <<< "It’s time again!"

How it Works

The command uses a guard file written to $XDG_DATA_HOME/every. If XDG_DATA_HOME is unset then it defaults to $HOME/.local/share.

The name of the guard file is derived from the arguments passed to every (using sha1) and the content of the guard file is a counter to keep track of how many times we have been called. As a convenience we also write the command to the guard file.

Once the counter reaches the value given via -n then every will remove the guard file and exec your command.

The command is implemented as a bash script and should work on both OS X and GNU/Linux.

Alternative Solution

If the external guard file is undesired or readability is not a concern, then an alternative approach is to use modular arithmetic with the UNIX epoch returned by date +%s. For an example see this post.

{{ numberOfCommentsTitle }}

{{ submitComment.success }}

Error Posting Comment

{{ submitComment.error }}