3

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?

  • 1
    I am afraid that, on standard Linux (if such thing exists), no such solution is available. There are commercial product, like $U that do the job, but you have to pay and configuration is not easy. – Archemar Oct 19 '14 at 20:25
  • 3
    You could write a "wrapper" script that checks how many time its target has been run and enforces the limits you want. In addition to cron, take a look at "at". – barrycarter Oct 19 '14 at 23:15
  • Thank you, both, for your comments. @barrycarter: If I understand correctly the 'at' command is for a job/taks to run once. If this is correct, then it doesn't quite match what I'm looking for. – camria Oct 26 '14 at 16:59
  • @camria Correct, but instead of putting a job in cron, you can just schedule it as many times as needed using 'at' (multiple at jobs), since you appear to be running it a finite number of times? – barrycarter Oct 26 '14 at 17:03
  • I see what you mean... yes, that would work if I don't need it to run like 30 or more times; otherwise, I guess it would get a bit cumbersome. Will give it a try :) – camria Oct 26 '14 at 17:07
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.