Using Cron Within Snaps

Can anyone help figure out how to do this, if it’s possible?

My desired scenario is, I have a snap called my-snap. I’d like for the user to be able to install it, and run my-snap start. This would create a cron job that would call the snap, by default, every hour. Running my-snap start 2h would specifically set it to run every 2 hours instead.

Running my-snap stop would delete the cron job, causing the snap to no longer run automatically.

Doing some research, I didn’t find a perfect solution. I couldn’t find anything with snaps and cron aside from the user manually configuring their system cron to run the snap, not the snap being able to configure this itself.

I then saw that snaps should be able to create systemd timers. I didn’t see documentation for how to actually do this or how to make the time customizable.

Thanks in advance.

I’m not sure how you can make the timer customizable, but if you’re okay with having the timer schedule statically defined in the snap, you can have a daemon in your snap set to run on a timer schedule, and then disable this daemon initially in the install hook and then your my-snap app would simply just enable or disable that daemon. So something like this for the app:

#/bin/bash -e
case "$1" in 
    start)
        snapctl start --enable "$SNAP_NAME.mysvc"
        ;;
    stop)
        snapctl stop --disable "$SNAP_NAME.mysvc"        ;;
esac

Then you would have an install hook that looks like this:

#/bin/bash
snapctl stop --disable "$SNAP_NAME.mvsvc"

The docs for the timer spec are here: Timer string format (admittedly they should be on docs.snapcraft.io but aren’t).

Also note that disabling the service on install may not work due correctly due to unfinished design at How to manage services with sockets/timers

2 Likes

This is very, very helpful. Thank you.