Skip to content

Instantly share code, notes, and snippets.

@spinpwr
Last active September 12, 2022 16:10
Show Gist options
  • Save spinpwr/b7c4fcaa726dd9bd9158dc12080e9c57 to your computer and use it in GitHub Desktop.
Save spinpwr/b7c4fcaa726dd9bd9158dc12080e9c57 to your computer and use it in GitHub Desktop.
bash script that reschedules it self to run at random time in crontab
#!/usr/bin/env bash
# Script that reschedules is self in crontab
# Should be added to crontab manually first
# Also add/call the "real job" (actual program) you want to run in crontab
# Comes with NO warranty, use at your own risk!
# Max range for added random time
days=30
hours=10
mins=59
# Get current cron jobs
cron=$(mktemp)
crontab -l > $cron
# Generate new random date
new_date=$(date -d "now + $((RANDOM % $days)) days $((RANDOM % $hours)) hours $((RANDOM % $mins)) minutes" +"%M %H %d %m * ")
# Update cron file
sed -i "s%.*$0%$new_date $0%g" $cron
# To apply might need -f switch depending on crontab version
crontab $cron
# Clean up temp
rm -f $cron
@spinpwr
Copy link
Author

spinpwr commented Sep 12, 2022

Based on answer and ideas from this stackoverflow question:
https://stackoverflow.com/questions/9049460/cron-jobs-and-random-times-within-given-hours

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment