Q: I have a simple one line script that uploads a photo taken by my webcam to a remote server (/sbin/runuser -l myuser -c ‘scp /var/ftp/pub/snap/20131209-232415.jpg [email protected]:www/cam/home.jpg). How can I run this as a cron job every 30 seconds?
A: This can be done, but not with cron alone. There is no mechanism to run a cron job any more frequently than one minute. This means you are limited to running your cron job once per minute.
One way you accomplish this is with a sleep in your script. For example, something like this:
#!/bin/bash # Run the command /sbin/runuser -l myuser -c 'scp /var/ftp/pub/snap/20131209-232415.jpg [email protected]:www/cam/home.jpg # Wait 30 seconds sleep 30 #Run the command again /sbin/runuser -l myuser -c 'scp /var/ftp/pub/snap/20131209-232415.jpg [email protected]:www/cam/home.jpg
The problem you can run into is timing issues since the command will take time to complete. So let’s say it takes 2 seconds for your upload to finish. This means that the second command in actually running 32 seconds after the cron job launched (SLEEP + TIME TO EXECUTE). This puts you in a possible situation of launching a cron job, on the next minute, before the previous iteration has completed.
You can use flock to get around this by creating a lock file. Below is a link to a good explanation of the basics of flock.
Bash Script Locking with flock
Resources for Scheduling Jobs in Linux
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Join Our Newsletter
- Bash Scripting (17)
- Basic Commands (50)
- Featured (7)
- Just for Fun (5)
- Linux Quick Tips (98)
- Linux Tutorials (60)
- Miscellaneous (15)
- Network Tools (6)
- Reviews (2)
- Security (32)
Leave a Reply