linux shell, keep task alive for specified time

I am looking for a tool to keep a task alive (restarting if necessary) for a specified amount of time (in seconds), and then kill it and stop. For example: keep_for 3600 rsync foo bar:faz should for try to synchronize a directory (restarting rsync in case of f.e. dropped connection), but explicitly kill rsync and stop respawning it after an hour.

I tried to write a shell script for that, but it was surprisingly difficult to write, with lots of edge cases (like child process not getting killed, or shell escaping issues). So... maybe there already is a tool for that?


If your system has Upstart, you can create an events file for your script/command and this may do what you want (if not now then possibly in a future version using planned features).

Here are a few bits of information from the events(5) man page:

  • Manual start:

    start on <event>
    Describes on what condition to start this job. Without this section, the job can only be manually started with the initctl(8) command.

  • Respawn:

    respawn
    This sets the daemon, service, and respawn flags for the job. The respawn flag means that the process will be restarted when it ends

  • Respawn limit:

    respawn limit [count [timeout]]
    This configures respawn limits. Respawn limits only apply if the respawn flag is set for the job; setting a limit does not automatically set respawning capability. If the process is respawned more than count times within an interval of timeout seconds, the job will be stopped automatically, and not restarted. The limit defaults to 10 times within 5 seconds.

See Getting Started.