12

I need to call a specific command in an interval of about 5 sec. How would I setup a daemon/process running in the background or something similar to do that? I looked at cronjobs, but the minimum interval seems to be 1 minute. Any advice is appreciated ;)

Fedora is the system.

EDIT the command would be a bashscript, so "watch" wouldn´t do it I think.

4 Answers 4

14

Why do you think 'watch' will not work?

$ cat periodic.sh
#!/bin/bash
echo $(date)
$ chmod +x periodic.sh

$ watch -n 5 ./periodic.sh
3
  • what if I log out? the script should continue running.
    – Björn
    Jan 19, 2011 at 15:13
  • It will stop, but you can use nohup watch -n 5 ./periodic.sh > periodic.log & and store the output.
    – naufraghi
    Apr 28, 2011 at 10:07
  • for piping use the '' quoting because th "command is given to "sh -c" which means that you may need to use extra quoting to get the desired effect"
    – andrej
    Mar 22, 2013 at 10:00
10
(
  while true
  do
    your-command-here
    sleep 5
  done
) &
disown
4
  • what is disown for? what if I run without it?
    – Björn
    Jan 19, 2011 at 15:09
  • @Marcel, disown removes the last job from the shell job table, making it sort of a daemon, like you asked. It is not a real daemon because it is still attached to terminal and is in the same process group, but it will keep running after you close the shell.
    – Juliano
    Jan 19, 2011 at 15:14
  • okay great, that would work :D Just for curiosity how would i "make" a daemon?
    – Björn
    Jan 19, 2011 at 15:24
  • @Marcel the simple way is to call daemon(3) from C or other language with library access (not from a shell script). This is the hard way.
    – Juliano
    Jan 19, 2011 at 15:35
2

Maybe with nohup? It's designed to let a job run after the shell is closed.

You can also use screens.

1

The watch command is appropriate in your case, i would use a terminal multiplexer (e.g. tmux, screen, etc.) and then run the command using

watch -n 5 ./script.sh

In that case even if you close the terminal or ssh connection to the machine the script would still be running.

The only limitation of this approach is that the script will run every 5 seconds only if it has completed its execution within that time interval.

1
  • Since the OP explicitly stated that in his opinion watch wouldn't do it, please explain why your answer overcomes this limitation or at which point you think the OP was mistaken about watch being unsuitable for the task.
    – AdminBee
    Nov 7, 2019 at 10:11

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.