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 myuser@mydomain.com: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 myuser@mydomain.com: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 myuser@mydomain.com: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
Join Our Newsletter
Categories
- Bash Scripting17 (17)
- Basic Commands51 (51)
- Featured7 (7)
- Just for Fun5 (5)
- Linux Quick Tips98 (98)
- Linux Tutorials65 (65)
- Miscellaneous15 (15)
- Network Tools6 (6)
- Reviews2 (2)
- Security32 (32)
- Smart Home1 (1)