2

I need to create a cron job that runs a bash script in background which does not end unless killed. The bash starts a process that should keep running for about 28 hours then I need another cron job to kill it. First cron runs every day at 0:00AM, starts the process. Second cron runs at 4:00AM and has to kill the process started the day before, leaving the one for the current day to run.

From what I searched, I should store the pid of the process in a file and then have the second cron access it but how and where? In the cron or in bash? Considering the process started by bash script does not end until killed, will the commands after ever execute?

EDIT: Ipor Sircer's solution solves the particular problem I have but I'd still like to learn how to export the PID in a file which another CRON can access.

  • 3
    Exactly 28 hours? If so, just run timeout 28h yourcronjobhere – thrig Dec 29 '16 at 17:54
  • Argh, too late to edit… echo "kill $$" | at 4am tomorrow if you're strict about the time of day (otherwise, yes, prefer timeout). – Ulrich Schwarz Dec 29 '16 at 18:02
  • 28 hours should be enough to finish. ok where does the echo kill command go? In the bash script? So the commands that come after the process start are still executed? Should I use & after the process in the bash script? – UrVal Dec 29 '16 at 18:15
  • 1
    I'm going to be obnoxious and point out that there's probably a better way to d whatever it is you're trying to do. – barrycarter Dec 29 '16 at 20:00
3

Use timeout command, it is much easier:

0 0 * * * timeout 28h script.sh
  • wow, this is an unexpected solution, no need to complicate it with 2 crons if one can do the job. I'd accept your answer but I'm really curious to know how the PID can be exported in this situation can you help with this as well? – UrVal Dec 29 '16 at 18:07
  • Also, I'd uprate but I don't have the 15 reputation minimum yet :( – UrVal Dec 29 '16 at 18:08

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.