Mastodon Feed: Post

Mastodon Feed

Boosted by jsonstein@masto.deoan.org ("Jeff Sonstein"):
blotosmetek@circumstances.run ("Szymon Sokół 🇵🇱🇪🇺🇺🇦") wrote:

Unsolicited Programming Suggestion (UPS)¹:
When you code a condition for executing some action every N days, think what should happen if your system is down at the time of scheduled execution. For example, this #Python example code:

if current_day == previous_day + N:
   action()
   previous_day = current_day

will fail miserably – your action will not happen ever again. Replacing == with >= will solve the problem – assuming you want your action to be executed as soon as possible if the scheduled time was missed. If, however, your preferred solution is to skip the missed event altogether, but execute the next event at correct time, the % (modulo) operator is your friend:

if current_day % N == 0:
   action()

Of course, this holds for intervals expressed in any units, not just days, you just need to calculate your current_whatever accordingly – for example, current_hour = int(time.time()) // 3600 or current_week = int(time.time()) // (7*24*3600) .

Now you may ask "What about cron, isn't it its role to handle such things?"
Well, yes, but cron doesn't allow you to specify, for example, "every other week", and if you think this crontab entry: 0 12 */9 * * something will run something at noon every 9th day, you're in for a surprise, and you haven't read man 5 crontab carefully – at least on Debian it says:

# Run once every 9th day, even across week, month, and year boundaries:
33 22 * * *     expr $(date +\%s) / 60 / 60 / 24 \% 9 > /dev/null || echo Wax the floor.

Yes, this is what is needed to have your action actually performed on every 9th day rather than on 9th, 18th and 27th day of every month.

¹ I'll probably be posting more such #UPS based on my own or my coworkers' real life experiences…