Where to insert a loop/timer? - python

I need to insert a loop to ensure that the following runs and appends to the txt file every hour and I am stuck on where to properly put the loop.
thanks in advance.
from datetime import datetime
from threading import Timer
def log(self, LOG_TAG, LOG_MESSAGE):
print('{}: {}'.format(LOG_TAG, LOG_MESSAGE))
now = datetime.utcnow()
print(now)
year = now.year
day = now.day
month = now.month
print('year = {}, month = {}, day = {}'.format(year, month, day))
with open('log_{}_{}_{}.txt'.format(year, month, day), 'a+') as f:
f.write('{} \t {}: {} \n'.format(now, LOG_TAG, LOG_MESSAGE))
if __name__ == "__main__":
log = Spider_Log()
tag = 'SPIDERLOG'
log.log(tag, 'test2')

You can use a different thread to keep track of time. Once the set interval of time has lapsed, it would trigger an event. Another thread can wait for this event and do the part of printing to the log file. You can refer to the following code -
import threading, time
from _datetime import datetime
def thread_to_keep_time(event):
while True:
#Set it to 10 seconds for testing.
time.sleep(10)
event.set()
def thread_to_trigger(event):
print("Waiting for event")
while True:
if event.wait():
now = datetime.now()
print('Print log at ' , now)
timer_event.clear()
timer_event = threading.Event()
threading.Thread(target=thread_to_keep_time, args=[timer_event]).start()
threading.Thread(target=thread_to_trigger, args=[timer_event]).start()
# wait for all threads to exit
for t in threading.enumerate():
if t != threading.current_thread():
t.join()

Related

How do I receive the updated time every time it is called in this function?

import time
seconds = time.time()
local_time = time.ctime(seconds)
print("Start Time:", local_time)
def bot():
x = 0
while x < 16:
time.sleep(1)
print("Time:", local_time)
x += 1
When I run this code it prints the initial time take before the function every time, I would like it to show the updated time every time local time is printed, can someone point me in the right direction?
Using a variable will not re-evaluate it. You'll need to calculate the time again each loop iteration
import time
def bot():
for x in range(16):
time.sleep(1)
seconds = time.time()
local_time = time.ctime(seconds)
print("Time:", local_time)
bot()

How to move time 2 hours forward and loop the code everytime the set time is met?

I want to loop my code when it reaches the end and move the set time forward by 2 hours whenever the code loops to beginning. How could I do it with existing code?
Editing the code as per 1st suggestion and adding loop:
import pynput
from datetime import datetime, timedelta
from threading import Timer
from pynput.keyboard import Key, Controller
import schedule
import time
count = 0
while count <3:
x=datetime.today()
y=x.replace(day=x.day+0, hour=16, minute=37, second=00, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+0.02
keyboard = Controller()
def bump():
keyboard.type("!d bump")
time.sleep (.1)
keyboard.press(Key.enter)
time.sleep (.1)
keyboard.release(Key.enter)
t = Timer(secs, bump)
t.start()
plus2 = x + timedelta(hours=2)
count +=1
t = Timer(secs, bump)
t.start()

How to match current date and specific date in Python

I'm developing a reminder app in Python. My question is when I execute my code. It should wait until current date equals to specific date. But it's not working, here's my code.
CODE:
from threading import Thread
from datetime import datetime, timedelta
# Current date, 8/15/2020 - 10:00
a = datetime.now()
# Specific date (1 minute later from current date), 8/15/2020 - 10:01
b = a + timedelta(minutes = 1)
# Reminder name
d = "stack reminder"
# Reminder list
c = {}
# Target function
def createThread():
while True:
if(b.second == a.second and
b.minute == a.minute and
b.hour == a.hour and
b.day == a.day and
b.month == a.month and
b.year == a.year):
print("worked")
# If thread name in reminder list
if d in c:
print("canceling")
t.cancel()
break
# Set thread and thread name and print thread name
t = Thread(target = createThread)
t.setName(d)
print(t.getName())
# Append reminder name to reminder list and print
c[d] = b
print(c)
# Start thread
t.start()
This code isn't working. Is if statement wrong? I'm creating Thread because while program waiting for specific date, I want to do different things. Where is my fault and how to run this code?
You are never updating the a variable again.
datetime.now() doesn't constantly update so you will have to call this in your thread.
a = datetime.now() in every iteration of your while loop.
At the moment you are never getting get your if condition to match as the time in a stays in the past.
Also you should be able to simplify this.
(b.second == a.second and
b.minute == a.minute and
b.hour == a.hour and
b.day == a.day and
b.month == a.month and
b.year == a.year):
To just simply
if b == a:
As both should be datetimes.
But its probably better to do use > in your condition as by using == you would have to match to the millisecond. Even matching to the second could cause issues and the condition might be missed.
i.e
If "a" (i.e the current time) >= "b" the time you want to check for.
Then fire the condition.
or put another way... If the current time is greater than or equal to the calendar entry time - then its time to alert the user.
if a >= b:
Complete Example:
from threading import Thread
from datetime import datetime, timedelta
# Current date, 8/15/2020 - 10:00
# Specific date (1 minute later from current date), 8/15/2020 - 10:01
b = datetime.now() + timedelta(minutes = 1)
# Reminder name
d = "stack reminder"
# Reminder list
c = {}
# Target function
def createThread():
while True:
a = datetime.now()
if a > b :
print("worked")
# If thread name in reminder list
if d in c:
print("canceling")
t.cancel()
break
# Set thread and thread name and print thread name
t = Thread(target = createThread)
t.setName(d)
print(t.getName())
# Append reminder name to reminder list and print
c[d] = b
print(c)
# Start thread
t.start()

Check for a file's availability for a certain time and then break

I've been trying to break a loop which is meant to look for a file in a certain location. My intention is to make my script look for that file for a certain time and then break whether the file is found or not but I can't get any idea.
How can I make the script wait for a certain time and then break when the time is up?
This is my script at this moment:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
while not os.path.exists(file_path):
time.sleep(1)
#is there any logic I can apply here to make the following line valid
# if waiting_time>=time_limit:break
print("Time's up")
Calculate the elapsed time by doing actual time minus start time by using time.time() function and assign a variable (file_exists in this code) which will be modified and check whether the file exist or not and use it for the loop.
As below:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
start = time.time()
file_exists = os.path.exists(file_path)
while not file_exists:
time.sleep(1)
file_exists = os.path.exists(file_path)
elapsed = time.time() - start
if elapsed >= time_limit:
break
else:
print("File exist.")
print(elapsed)
print("Time's up")
def exists_timeout(path, timeout):
"""Return once <path> exists, or after <timeout> seconds,
whichever is sooner
"""
timer = timeout
while (not os.path.exists(path)) and timer > 0:
time.sleep(1)
timer -= 1
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
cTime=0
time_limit = 5
while cTime<time_limit:
if os.path.exists(file_path)==False:
cTime=cTime+1
time.sleep(1)
else:
pass
if cTime==5:
responce="Time's Up"
else:
responce='Found'
print(responce)
As roganjosh commented, it would be simpler if you used time stamps. I have added relevant code below:
import os
import time
from datetime import datetime, timedelta
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = datetime.now() + timedelta(seconds=5)
present = datetime.now()
while (not os.path.exists(path)) and present < time_limit:
present = datetime.now()
if present >= time_limit:
print("Time's up")
break
time.sleep(1)
Here's how to do it with the threading.Timer() class. These can be configured to delay a specified amount of time and the call as function of your choosing.
import os
from threading import Timer
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
# Timer callback function.
def timeout():
global time_ran_out
time_ran_out = True
time_limit = 5
time_ran_out = False # Define variable the callback function modifies.
timer = Timer(time_limit, timeout) # Create a timer thread object.
timer.start() # Start the background timer.
while not os.path.exists(file_path):
time.sleep(1)
if time_ran_out:
print('Times up!')
break
print("Done")
To check for the availability of a file in a certain location you can try the following. The script will break as soon as the file is found otherwise it will wait upto 5 seconds for the file to be available before breaking.
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_to_wait = 5
time_counter = 0
while not os.path.exists(file_path):
time.sleep(1)
time_counter += 1
if time_counter > time_to_wait:break
print("done")

Stopping Stopwatches

I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():

Categories