I want to run an rsync command at midnight but make it stop at 8am. How can i schedule the start AND END of a command?

5,115

Solution 1

Add a second crontab entry that kills rsync at 8 am. Another option would be to start rsync in the background and have the script loop until 8 am before it kills the process:

#!/bin/bash

rsync ... &
pid=$!

while /bin/true; do
  if [ $(date +%H) -ge 8 ]; then
    kill -TERM $pid
    exit 0
  else
    sleep 60
  fi
done

Solution 2

You could have a shell script write the rsync PID into a file at a fixed location. I would get the PID by launching rsync in the background (append &) and use $!.

rsync blah/ remote:blah/ &
echo $! > pidfile

Then another cron job at 8 am would read that file and put the result into RSPID.

RSPID=`cat pidfile`

Then run ps $RSPID | grep rsync to see if it is still running, then do kill $RSPID.

Something along those lines should work.

You could also put the kill command into the shell script. Launch rsync in the background and sleep 8 hours, then kill the rsync.

Share:
5,115

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    I want to run an rsync command at midnight but make it stop at 8am. How can i schedule the start AND END of a command?

    I've looked into cronjobs but that will only start at a certain time. Any ideas on how to end this process? Ill be running it from OS X. I thought about logging in as a new ssh user and just using a cronjob to start a bash script to kill that connection but that seems like overwork.

    • Admin
      Admin about 11 years
      Have you tried using ulimit -t to cap the amount of time it can execute?
    • Zan Lynx
      Zan Lynx about 11 years
      @RandyHoward: ulimit -t will limit the CPU time used, but rsync generally uses very little CPU, being limited by I/O.
  • Judking
    Judking about 9 years
    Could you give me the official URL to the explanation of '$!'? I couldn't google it coz it's somewhat recognized as special characters by Google.
  • Ansgar Wiechers
    Ansgar Wiechers about 9 years
    @Judking It's documented in the section PARAMETERS of the bash man page (under "Special Parameters"). It's also explained in chapter 9.1 of the Advanced Bash Scripting Guide (under "Other Special Parameters").