Reputation: 441
im new to python and have a loop that pulls data from a json. i have set variables with if and else statements so when the variables match, it sends a notification. however, i would like add another if statement within the if so it displays the data in the window but the other if time exceed 5 minutes, send notification.
i tried to set something like
import time
time = time.gmtime().tm_min
while True:
if price <= buy:
print ("BUY!")
if time > timeout:
send message code
timeout = time.gmtime().tm_min + 1
if timeout > 59:
timeout = 00
since the script is running on a loop, i think the time has to keep updating. once the if statements are triggered, send a message and add 5 minutes to the time variable so that on the next loop if the statement is true, dont run if the time hasnt exceeded 5 minutes. i say 5 minutes but in the actual code i have 1 minute for 2 reasons. the first reason is because the first if statement doesnt last that long. after about 30minutes it goes further away from the price. the 2nd reason is because i dont know how to wrap around in python after 59 in time :P.
Upvotes: 0
Views: 1032
Reputation: 277
Here is code which prints "BUY" every time the price is above the threshold, and sends a notification if no notifications have been sent in the previous 60 seconds.
import time
import random
def get_price():
return random.random()
buy = 0.2 # Threshold price for buying
notification_time = 0 # This initial value ensures that the first notification is sent.
while True:
if get_price() <= buy:
print ("BUY!")
if time.time()-notification_time > 60:
notification_time = time.time()
print("Sending notification")
time.sleep(1) # Wait 1 second before starting the next loop
Especially in python, you want to avoid doing stuff manually, like you do by taking the tm_min from the time object. You can usually get better results by using the existing libraries, such as subtraction between two timestamps.
Upvotes: 0
Reputation: 1210
from time import perf_counter
while True:
start_time = perf_counter() + 300 # Set limit to 5 minutes (60 seconds * 5)
if price <= buy:
print ("BUY!")
if perf_counter() > start_time:
#send message code
Upvotes: 2