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?
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.
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)
You can use time.sleep
count = -1
while(not abort):
count = (count+1) % 100
if count == 0:
print('hello world!')
time.sleep(3)
I am considering your code takes less than 5 minutes, but the execution time for each run is not constant.
import time
while True:
t= time.time()
# your code goes here
................
........
t= time.time()-t
time.sleep(300-t)
Related
is there any way I can run python code in this way:
main code will run all the time ,
once every 5 min will run another function while running the main code.
my code is reading gps signal and send it to my server every 5 seconds.
I have to run another code that check the device cpu\file\temp every 5 min (this part take around 30 seconds )
can both of them run at the same time while still getting gps?
I have the GPS code ready and also the Check code ready - how do I combine them (if it's possiable)
Thanks ,
This might answer your question: Running Two Script at Once Using Bash
Based on the answer here, all you'd have to run is:
python script1.py &
python script2.py &
You can use the threading module, to do this task: it allows you to run functions as different processes seperate from the main program. Threading Documentation
I think you should get what you want with the following code:
import threading
def gpsJob():
threading.Timer(300.0, gpsJob).start()
# Here goes your GPS-code
gpsJob()
if __name__ == '__main__':
# main code
I got temperature, pressure, and altitude readings on my PI using a sensor:
The problem is, to see the results, I have to execute the code.py every time by myself. I am trying to automate it somehow so it will keep running itself for the time I want.
Once that is automated, would like to save the results and analyze the output after some time.
Is there a way I can write code for both the tasks?
Thank you.
There are two things required here. First a script i.e code.py to log the functional behavior like temperature, pressure, and altitude readings along with error/response during the process. Another is the script executions logs i.e a success or failure during the scheduled time and other system logs.
For first job, you have to do by your self but ensure to have a logger module in place to log the process flow.
For Second job, you can use OS provided scheduler crontab for Linux based os. For example to execute script every minutes
* * * * * python /home/script/code.py > /home/script/code.log 2>&1
For more about scheduler jobs, you can refer here
The time module is your friend here. You can set up an infinite loop with while True: and use time.sleep(secs) at the end of the loop (after output).
I'd use additional controller script like this:
import subprocess;
import time;
import sys;
x = True;
while x:
while exit_code!=0:
try:
exit_code = subprocess.check_call(['python', 'collect_data.py', '-cli_args_if_needed']);
except:
print(sys.exec_info()[1]);
print('Relaunching in 5 seconds');
time.sleep(5)
Let's say I have the following python program:
def Is_it_Midnight(args):
print("It's midnight!")
and I want the .py script to execute itself when a certain condition is true, say "when the clock strikes midnight".
Is that possible?
You can use the threading library to have the routine restart itself periodically. In this specific case, every 86400 seconds (1 day).
modify your code to:
import threading
import time
def Is_it_Midnight(args):
threading.Timer(86400, Is_it_Midnight).start()
print("It's midnight!")
Then you just have to get the code to run at midnight the first time. Something like:
seconds = time.time()
since_midnight = seconds % 86400
time.sleep(86400-since_midnight)
Is_it_Midnight()
I'm not sure how you'd handle passing args into the routine.
There are a few options to run a script.
My favorite is to create myscript.py and within it define a function, let's say def alarm()... and then in your main script:
import myscript
And when the time comes, call:
myscript.alar()
There is another way, you can call execfile("myscript.py")
Looked at all the similar questions but unable to get the syntax correct. I have a python script that runs a single command at the moment. What I need to do is have this command repeat itself over and over...indefinitely...at certain intervals. Here is my script:
#! /usr/bin/env python
import sys
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR
p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100 )
if p:
p.show()
This runs fine from the command line. However I need it to repeat every 30 seconds or 1 minute. How would I tell it to do that inside the script? I know I can probably set this up as a cron job but I'd like to know how to script it. Thanks!
You can use the time module's sleep() method inside a while True loop.
#! /usr/bin/env python
import sys
import time
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR
while True:
p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100)
if p:
p.show()
time.sleep(60) # sleep for one minute
you can put a infinite while loop and add sleep of 30 seconds in every iteration. The other option could be set the script into cron job.
The advisable option is cronjob as in case python script exit due to any exception or error, cron can re-run it in next cycle.
Create a while loop. True is always True, so the loop keeps running. After the commands wait a while.
#! /usr/bin/env python
import sys, time
interval = 60 #1 minute
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR
while True:
p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100 )
if p:
p.show()
time.sleep(interval)
The infinite loop with the sleep as mentioned in the above answers is the simplest way to do what you want. However, if you do that, your program becomes a daemon which you have to monitor and make sure is running. This has some costs that you should be aware of up front.
I would prefer to use cron to run it every n minutes or something similar. Yet another way, which is similar to the inifinite loop is to the use the python sched module to run a mini cron like system inside your program.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to repeatedly execute a function every x seconds in Python?
Hi so here is the code I have:
client = myclient(info1,info2)
sellor()
Contractor()
It works perfectly but what I would like to do is to make python launch that code every 60 seconds indefinitely...
I don't actually understand how I have to put the code together with the time loop
Any help is appreciated
Thank's
If the 60 seconds ignores the time it takes to execute your code):
from time import sleep
while True:
sleep(60)
# your code here
but if the 60 seconds takes into account the time it takes to execute your code:
from time import sleep
from os import fork
while True:
sleep(60)
fork() # create child process
# your code here
Use the sleep method. Just create a loop (while, for, whatever) and sleep for 60 secs every iteration.
import time
while True:
client = myclient(info1,info2)
sellor()
Contractor()
time.sleep(10)
hope it works,all the best mate
import time
repeat_time = 3.0
while True:
start_time = time.time()
# Your code goes here
time.sleep(max(repeat_time - (time.time() - start_time), 0.0))
And your code will be executed exactly every "repeat_time"
You could use sleep as already mentioned. But because there may be a variable amount of time needed for your own functions to run, this wouldn't necessarily mean your functions are run every 60 seconds.
If it was important that the period between each start of your functions is closer to 60 seconds, you could use time. I haven't tried this but something like
import time
while True:
# Get the current time
startTime = time.time()
# Your functions
client = myclient(info1,info2)
sellor()
Contractor()
delay = True
while delay:
if time.time() - startTime > 60:
delay = False # Break the delay
You might also think of just scheduling the task through windows scheduler. The benefit here would end the script once run and then execute the script again after scheduled interval. In the second approach it seems that the script instance process would continually run and only use the sleep function to do nothing for the specified time. I take it this way if the scripts fails at any instance you might have to keep a check to restart the script. While as a scheduled activity the script will be executed in any case at that specified intervals.
You might also not want the process thread to be kept running for the python script executed. I will research on this and you might get to hear form our other folks in the mean while.
Regards,
Harshal