2

I'm trying to automatically run a script once every minute. But it might take more than 1 minutes sometimes & hence I have to have a lock on the script while it is running so that only one instance of the script can run at any given time.

My cronjob is as follows,

* * * * * root /usr/bin/flock -w 0 /var/cron.lock /pythonScripts/readPushData.py

My python script is set an executable using,

chmod a+x readPushData.py

The python compiler is set at the top of the script like,

#!/usr/bin/python3.5

The script can be run manually using './readPushData.py', but when I try to run it using a cronjob it doesn't work. Why is this happenning?

  • cron will only run proper commands. Have you tried running root /usr/bin/flock -w 0 /var/cron.lock /pythonScripts/readPushData.py? – Milliways Mar 26 '19 at 07:42
  • you mean run this on shell? – Ashan Madusha Vithanage Mar 26 '19 at 08:04
  • I found this from https://serverfault.com/questions/748943/using-flock-with-cron – Ashan Madusha Vithanage Mar 26 '19 at 08:09
  • You have taken this out of context, and failed to specify what you actually did to set cron up. – Milliways Mar 26 '19 at 09:38
  • Does it work if you replace your script with a dummy script which just sleeps for two minutes? – Dmitry Grigoryev Mar 26 '19 at 10:07
  • 1
    This likely has nothing to do with the lock. If the lock matters at all, it is probably a secondary problem. Python scripts (or scripts and programs generally) that run from the command line will not necessarily run in cron due to having a different environment setup. There are multiple posts on that here, and the question really has nothing to do with Raspberry Pi. It's general Linux. As regards timing, you should probably consider having cron launch this once and having the script itself sleep between times that you want it to work. – Brick Mar 26 '19 at 15:33
  • https://raspberrypi.stackexchange.com/questions/2157/default-shell-for-cron-issue/2158#2158 and https://raspberrypi.stackexchange.com/questions/70546/cant-get-python-script-to-execute-using-crontab-or-initd-or-systemd-or-rc-local/70582#70582 – Brick Mar 26 '19 at 16:28

1 Answers1

1

I found the solution for running one instance of my script at a time using this [https://raspberrypituts.com/raspberry-pi-simple-cron-jobs-explanation/][1]

Then I used the following in /etc/cron.d/python to setup the cronjob

* * * * * root /usr/bin/python3.5 /pythonScripts/readPushData.py

Then I rebooted the system. It works like a charm. Thank you all for your comments!

  • Please accept your own answer with a click on the tick on its left side. Only this will finish the question and it will not pop up again year for year. – Ingo Dec 28 '19 at 21:09