Python how to freeze program? [duplicate] - python

This question already has an answer here:
How to start/stop a Python function within a time period (ex. from 10 am to 12:30pm)?
(1 answer)
Closed 2 years ago.
Note: read my comments on the provided answer, it doesn't work
I have a python program which runs every 5 seconds like this:
def main():
start_time = time.time()
while True:
if not execute_data():
break
time.sleep(5.0 - ((time.time() - start_time) % 5.0))
The question is how can I make it run from 7:00 to 23:00 only? I don't want to use my computer resources at times where I'm sure my program won't be helpful...

You can use datetime.datetime.strptime() and datetime.datetime.strftime():
from datetime import datetime
import time
def str_to_time(string):
return datetime.strptime(string, "%H:%M")
def main():
start = '7:00'
end = '23:00'
while True:
now = str_to_time(datetime.now().strftime("%H:%M"))
if str_to_time(end) > now > str_to_time(start) or str_to_time(end) < now < str_to_time(start):
print('Working...')
time.sleep(5)
main()

Related

multithreading in python and time module [duplicate]

This question already has an answer here:
perf_counter is returning wrong time
(1 answer)
Closed 5 months ago.
I'm trying to learn multi_threading in python but when I try to print time.perf_counter() in order to see how much time the Main Threading takes to run the program which is in charge the output is a huge number (614691.9609577), but it should not even be 2 seconds. Can you explain the reason of this problem?
Thanks
import threading
import time
def have_breakfast():
time.sleep(3)
print("You had breakfast")
def make_bed():
time.sleep(4)
print("You made your bed")
def study():
time.sleep(5)
print("You finish studying")
x = threading.Thread(target = have_breakfast, args = ())
x.start()
y = threading.Thread(target = make_bed, args = ())
y.start()
z = threading.Thread(target = study, args = ())
z.start()
x.join()
print(threading.active_count())
print(threading.enumerate())
print(time.perf_counter())
From here:
time.perf_counter():
Return the value (in fractional seconds) of a performance counter,
i.e. a clock with the highest available resolution to measure a short
duration. It does include time elapsed during sleep and is
system-wide. The reference point of the returned value is undefined,
so that only the difference between the results of two calls is valid.
Use perf_counter_ns() to avoid the precision loss caused by the float
type.
New in version 3.3.
Changed in version 3.10: On Windows, the function is now system-wide.
In your case if you want to measure time you need to subtract two time intervals. E.g.:
t1_start = time.perf_counter()
# your code...
t2_stop = time.perf_counter()
print("Elapsed time: ", t2_stop - t1_start)

How to precisly sample a sensor-signal in Python [duplicate]

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 4 years ago.
I want to write a Python program that will sample a sensor at a fixed sampling rate. Is there any elegant way of doing this?
Currently, I am using the time.time and time.sleep commands to enforce this manually. While this does work, it is creating a small drift. Also, it seems to be a not very nice way of doing so, and I hope there is a more pythonic way of doing this:
def mock_signal(x):
# Just a random number as the sensor signal
return np.random.random()*x
def sampling(fs=1, x=1):
T = 1/fs # sampling period
t_ground = time.time()
while True:
t_start = time.time()
y = mock_signal(x)
print('%.5f | Sensor Value %.2f' % (t_start - t_ground, y))
t_duration = time.time()
# Sleeping for the remaining period
time.sleep(T - (t_duration-t_start))
Ideally, I would like to have a function or class that would sample the sensor (basically call the 'mock_signal' function) and append the new sample to a list or array. The latest entry in said array should than be accessible by a call similar to the multiprocessings Connection.recv()
Thanks in advance :)
May you can try something like that.
import threading
t_ground = time.time()
def sampling():
t_ground = time.time()
threading.Timer(T, sampling).start()
t_start = time.time()
y = mock_signal(1)
print('%.5f | Sensor Value %.2f' % (t_start - t_ground, y))
It's just an example. You need to change it to your need.

timeout for 10 seconds while loop in python [duplicate]

This question already has answers here:
How would I stop a while loop after n amount of time?
(11 answers)
Closed 9 months ago.
What is the best way to timeout while loop in python
say:
while not buff.endswith('/abc #'):
After 10 secs, if it does not match, break the loop.
Thanks
You can record the time before the loop, then inside the while loop you can compare the current time, and if it's > 10 seconds, you can break out of the while loop.
Something like:
from datetime import datetime
start_time = datetime.now()
print(start_time)
while not buff.endswith('/abc #'):
print('waiting')
time_delta = datetime.now() - start_time
print(time_delta)
if time_delta.total_seconds() >= 10:
break
If your only concern is to end the loop after 10 seconds, try the below code.
from datetime import datetime
t1 = datetime.now()
while (datetime.now()-t1).seconds <= 10:
#do something
print(datetime.now())
Else check for the time difference inside the loop and break it. Like,
t1 = datetime.now()
while not buff.endswith('/abc #'):
if (datetime.now()-t1).seconds > 10:
break
You can use interrupting cow package and put you code inside a with management statement.
import interruptingcow
TIME_WAIT=20 #time in seconds
class TimeOutError(Exception):
"""InterruptingCow exceptions cause by timeout"""
pass
with interruptingcow.timeout(TIME_WAIT, exception=TimeOutError):
while not buff.endswith('/abc #'):
pass #do something or just pass
As long you don't use interruptingcow with another systems that implements SIGALARM eg. stopit, python-rq. It will work

Implementing a timer(countdown) that runs pararell with the game logic [duplicate]

This question already has answers here:
How to set time limit on raw_input
(7 answers)
Closed 6 years ago.
I have created a mathematical quiz game that prints and equation to the user like, 5 + 3 = ?, and waits for the result. If the answer is right the user wins if not the user loses. I want to extend the game and add a feature that places a time limit of 3 seconds for the user to answer, if he don't the he loses.
At the beggining I tried using the time module and the time.sleep() function but this also delayed the whole program's logic.
Here is an idea with pseudo code:
if (answer = wrong || time = 0)
lost...
if you want to check if the user took to long when he answered you can use the time module to calculate the diffrence:
start_time = time.time()
show_question()
answer = get_answer()
end_time = time.time()
if (answer = wrong || end_time - start_time > 3)
lose()
if you want the user to loose when 3 seconds as passed (without waiting for them to input a answer) you will have to use threading, like this:
timer = threading.Timer(3, lose)
show_question()
answer = get_answer()
timer.cancel()
if (answer = wrong)
lose()

Pause for loop every x minutes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How can I create a loop that sleeps a random amount of time every X minutes, where X is also a random duration of time?
I also want to be able to specify the upper and lower boundaries of the random durations of both times.
You could try something like this:
import random
from datetime import datetime
from time import sleep
# Randomly select a time between 20 to 30 minutes
# before sleeping.
random_time_duration = random.randint(1200,1800)
# Randomly sleep between 60 to 120 seconds.
sleep_duration = random.randint(60,120)
# This is the start time of of loop used to track
# how much time has passed.
old_time = datetime.now()
while True:
# Check if the randomly selected duration has
# passed before running your code block.
if (datetime.now()-old_time).total_seconds() > random_time_duration:
sleep(sleep_duration)
# Reset all the time variables so the loop works
# again.
random_time_duration = random.randint(1200,1800)
sleep_duration = random.randint(60,120)
old_time = datetime.now()
else:
# Put your code in here.
pass
sleep_time = 50 #time to sleep in seconds
difference = 30
sleep_time = random.randint(sleep_time-difference, sleep_time+difference)
sleep_every = 10 #ammount of time to wait before sleeping in minutes
cur_time = time.time()
while True: #change to your for loop
if time.time() - cur_time >= sleep_time * 60:
time.sleep(sleep_time)
cur_time = time.time()
else:
#your code here
print time.time() - cur_time
can obviously be adapted to a function but this works perfectly
here is a sample code using datetime.now() and timedeltas to calculate the next interval somewhat randomly, this has an advantage over using time.time or similar since that would fail at midnight since the date would also be important in that case:
import time
import random
import datetime
sleep_duration = 1 #seconds
min_sleep_interval = max_sleep_interval = 3 #in seconds
_TIME_TO_SLEEP = datetime.datetime.now()
def maybe_sleep():
#using a singleton class you could avoind using globals
global _TIME_TO_SLEEP
if datetime.datetime.now()>= _TIME_TO_SLEEP:
time.sleep(sleep_duration)
seconds_to_wait = random.randint(min_sleep_interval, max_sleep_interval)
next_delay = datetime.timedelta(seconds= seconds_to_wait)
_TIME_TO_SLEEP = datetime.datetime.now() + next_delay
Then just call maybe_sleep() every iteration and adjust the constants to your liking (maybe make them less constant ;)
As a demo:
for i in range(10000):
maybe_sleep()
print(i)
You can try this :
import datetime
import time
import random
sleep_duration = 60
previous_sleep = datetime.datetime.now()
random_offset = random.randint(-5, 5)
while(True):
delta = (datetime.datetime.now() - previous_sleep).total_seconds()
if delta < 60 * (20 + random_offset):
# Do stuff
time.sleep(1)
continue
else:
previous_sleep = datetime.datetime.now()
random_offset = random.randint(-5, 5)
time.sleep(sleep_duration)
This program would sleep for 60 seconds every 15-25 minutes, depending on the random offset computed.

Categories

Resources