I'm learning Linux at the moment and were doing some exercises scheduling jobs with cron and crontab, but I'm wondering if it's possible to limit the amount of times that the scheduled job is ran. From the man pages, I can see how to schedule the job to execute periodically, but I haven't found a way to give a specific number of times to be executed, or a date on which it should stop running the job. Is it possible to do this?
Example: A job that runs hourly, until "Mon Feb 4 08:30:00 UTC 2019" (Unix timestamp 1549269000) would look like
@hourly [ "$( date +\%s )" -lt 1549269000 ] && /path/to/my-script.sh
The job would technically still run, but it would not execute the script after the given timestamp.
Similarly, a job that runs only five times hourly:
@hourly ( f="$HOME/job.count";c=0;[ -f "$f" ] && read c <"$f"; echo "$(( c + 1 ))" >"$f"; [ "$c" -lt 5 ] ) && /path/to/my-script.sh
The above job, beautified:
( f="$HOME/job.count" c=0 [ -f "$f" ] && read c <"$f" echo "$(( c + 1 ))" >"$f" [ "$c" -lt 5 ] ) && /path/to/my-script.sh
This uses a state file,
$HOME/job.state, to store the number of times the job has executed. If the file exists, the number in it is read into
c, and then immediately written back to the same file, incremented. If the number is less than five, the script is executed.
Again, the job would run every hour regardless of the contents of the state file, but the script would only be run if the value in the state file was less than five.