I need to run a bash program at scheduled times (based on local time) on my Ubuntu 16.04. For instance, this is what I need:

Mon-Thursday, 10AM to 6PM AND Friday 10AM to Saturday 6PM: bash runme.sh

And once the clocked reached the end, kill -9 the program execution.

What's the best way to achieve that, maybe through a bash script?

  • I can write a code in Java to achieve that, but I prefer a bash code instead. – Tina J Feb 13 '18 at 1:22
  • I mean it can be any language. As long as I can simply run it and change it myself, it is fine! – Tina J Feb 13 '18 at 1:23
  • 1
    No! Looks like cron is the hero here. – Tina J Feb 13 '18 at 1:35
  • Does the script require any special permissions? Sudo? A display? Access to another application? Will the script run as your user? Root? A different user? A system user? – user535733 Feb 13 '18 at 1:42
  • Yes cron will definitely start your jobs at 10am M-T-W-T-F. Your script can shut itself down at 6pm M-T-W-T and Saturday. – WinEunuuchs2Unix Feb 13 '18 at 2:40

The simplest but, far from elegant, way to do that is writing a small process monitor.

Let's say your monitor is named monitor.sh, write this inside it:


# Runs your runme.sh in background
/location/of/your/runme.sh &

# Gets the PID of runme.sh

# Sleeps how much time you need:
sleep 8h 

# Kills the process:
kill -9 $RUN_ME_PID

Since it is a scheduled job, use cron to start it for you:

Append this in the end of /etc/crontab (as root):

# m h dom mon dow user  command
 00 10 *   *  1-4 tina  /location/of/your/monitor.sh > /your/output.log

Do the same for your friday batch, but change your monitor.sh for your needs.

Don't forget to mark monitor.sh as an executable:

$ chmod +x monitor.sh

For more information, check cron man-pages or some useful examples here

| improve this answer | |
  • If Friday you are sleeping 32 hours if I read the project scope correctly. – WinEunuuchs2Unix Feb 13 '18 at 18:12
  • Yes, indeed. Another solution is using the "self shutdown approach" as you pointed in the answer above. :) – Girol Feb 13 '18 at 18:15
  • Another solution is use the command at at the end of the script and schedule the kill -9 time – Girol Feb 13 '18 at 18:21
  • hi, if the runme.sh kicks off a application, will the application be killed when the process is kill -9 at the end? The process id is for the runme.sh I guess so does that also kill spawned processes? – hydev Jul 17 '19 at 7:33

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.