Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write python script that is executed every 5 minutes

I need to write a python script that autostarts on boot and is executed every 5 minutes on a raspberry pi. How can this be done? in particular, how can I avoid having a script locking up the cpu running a infine loop waiting for the 5 minutes to be over?

like image 596
user2452250 Avatar asked Nov 29 '22 15:11

user2452250


2 Answers

You can easily use cron for this task (schedule to run Python script). ;)

How to setup cron

I suppose that you have cron installed already; if not, then install some (vixie-cron for an example).

Create a new file /etc/cron.d/<any-name>.cron with the following content:

# run script every 5 minutes
*/5 * * * *   myuser  python /path/to/script.py

# run script after system (re)boot
@reboot       myuser  python /path/to/script.py

where myuser is the user to run the script (it shouldn’t be root if possible, for security reasons). If this doesn’t work, then try to append the content to /etc/crontab instead.

You might want to redirect stdout/stderr of the script to file, so you can check if everything works fine. This is same as in shell, just add something like >>/var/log/<any-name>-info.log 2>>/var/log/<any-name>-error.log after the script path.

like image 133
Jakub Jirutka Avatar answered Jan 14 '23 15:01

Jakub Jirutka


Use schedule

  • wrap the scrip in a function
import schedule 
import time 


def func():
    print("this is python")

schedule.every(5).minutes.do(func)

while True:
    schedule.run_pending()
    time.sleep(1)
like image 20
Prakash Vanapalli Avatar answered Jan 14 '23 15:01

Prakash Vanapalli