Skip to content

Instantly share code, notes, and snippets.

@alainwolf
Last active December 24, 2024 17:51
Show Gist options
  • Save alainwolf/931316e4f5af0c45b352a1823ec3321c to your computer and use it in GitHub Desktop.
Save alainwolf/931316e4f5af0c45b352a1823ec3321c to your computer and use it in GitHub Desktop.
Create crontab lines with scheduled random times
#!/usr/bin/env bash
# ****************************************************************************
# Create radom cron job starting times
# for hourly, daily, weekly, monthly or yearly jobs
#
# https://gist.github.com/alainwolf/931316e4f5af0c45b352a1823ec3321c
# Copyright (C) 2024 Alain Wolf
# ****************************************************************************
# What kind of shedule do you want to create?
# hourly, daily, weekly or monthly
_SCHEDULE="$1"
# If three arguments are given, use the second as user and the third as the
# schduled command
if [ -n "$3" ]; then
_USER="$2"
_CMD="$3"
printf "# min\thour\tmday\tmonth\twday\tuser\tcommand\n"
# If two arguments are given, use the second as command to schedule
elif [ -n "$2" ]; then
_CMD="$2"
printf "# min\thour\tmday\tmonth\twday\tcommand\n"
else
printf "# min\thour\tmday\tmonth\twday\n"
fi
# Generate random values within the correct ranges
rand_min=$((RANDOM % 60))
rand_hour=$((RANDOM % 24))
rand_mday=$((1 + RANDOM % 28))
rand_month=$((1 + RANDOM % 12))
rand_wday=$((RANDOM % 7))
# Determine the cron schedule based on the provided schedule type
case "${_SCHEDULE}" in
hourly)
printf " %s\t%s\t%s\t%s\t%s" "$rand_min" "*" "*" "*" "*"
;;
daily)
printf " %s\t%s\t%s\t%s\t%s" "$rand_min" "$rand_hour" "*" "*" "*"
;;
weekly)
printf " %s\t%s\t%s\t%s\t%s" "$rand_min" "$rand_hour" "*" "*" "$rand_wday"
;;
monthly)
printf " %s\t%s\t%s\t%s\t%s" "$rand_min" "$rand_hour" "$rand_mday" "*" "*"
;;
yearly)
printf " %s\t%s\t%s\t%s\t%s" "$rand_min" "$rand_hour" "$rand_mday" "$rand_month" "*"
;;
*)
echo "Usage: $0 hourly|daily|weekly|monthly|yearly [user] [command]"
exit 1
;;
esac
# Append user and command if provided
if [ -n "$_USER" ]; then
printf "\t%s" "$_USER"
fi
if [ -n "$_CMD" ]; then
printf "\t%s" "$_CMD"
fi
# Print a newline at the end
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment