0

I'm using the code

#!/bin/bash
while :; do
    ffmpeg -re -i "input" output.mp4
done

to loop a .sh file. Is there a way to edit this so it starts at 5pm CST every day and then stops at 9pm CST? Like a timer, so it doesn't run 24/7, but starts and stops itself like a task on Windows?

2
  • 2
    Google "cron" .. – szatmary Mar 4 '17 at 7:36
  • As said, look at cron: you can start the job at 5pm and kill it at 9pm. I would add a bit of code to handle a SIGKILL in your script, if you need to do anything before quitting. – Alessandro Dotti Contra Mar 4 '17 at 22:29
2

Try this:

#!/bin/bash

work() {
    # put your job here e.g.
    ffmpeg -re -i "input" output.mp4
}

echo "Launching background job..."
work &
workPID=$!
RUNNING=true

while true; do
    # If no child process, then exit
    [ $(pgrep -c -P$$) -eq 0 ] && echo "All done" && exit
    HOUR="$(date +'%H')"
    if [ $HOUR -ge 17 -a $HOUR -lt 21 ] ; then
        if [ "$RUNNING" == false ]; then
            echo "Start work..."
            kill -CONT $workPID
            RUNNING=true
        fi
    else
        if [ "$RUNNING" == true ]; then
            echo "Stop work..."
            kill -TSTP $workPID
            RUNNING=false
        fi
    fi
    sleep 2
done

The script launches the job as a child process with work &, then monitors that process and freezes/unfreezes it as required.

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.