Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create a program which takes a target time (like 16:00 today) and counts down to it, printing each second like this:
...
5
4
3
2
1
Time reached
How can I do this?
You can do this using python threading module also, something like this :
from datetime import datetime
import threading
selected_date = datetime(2017,3,25,1,30)
def countdown() :
t = threading.Timer(1.0, countdown).start()
diff = (selected_date - datetime.now())
print diff.seconds
if diff.total_seconds() <= 1 : # To run it once a day
t.cancel()
countdown()
For printing "Click Now" when countdown gets over, you can do something like this :
from datetime import datetime
import threading
selected_date = datetime(2017,3,25,4,4)
def countdown() :
t = threading.Timer(1.0, countdown)
t.start()
diff = (selected_date - datetime.now())
if diff.total_seconds() <= 1 : # To run it once a day
t.cancel()
print "Click Now"
else :
print diff.seconds
countdown()
This will result in something like this every second :
2396
2395
2394
2393
...
Related
This question already has answers here:
How to share a variable between 2 threads
(1 answer)
What is the use of join() in threading?
(12 answers)
Closed 1 year ago.
I have a while True loop that needs to be run in the background to update a variable and a function that needs to return that same variable.
I tried this as a test:
import threading
downspeed = 0
def updating():
while True:
downspeed = downspeed+1
def main():
while True:
print(downspeed)
u = threading.Thread(name='background', target=updating)
m = threading.Thread(name='foreground', target=main)
u.start()
m.start()
But it only returns 0
Your code is not really a sufficient test. The test ought to include:
Allowing some time for the threads to run to see what they do.
Make the threads sleep, at least for a little time, to allow task switches to occur.
See this code:
import threading
import time
can_run = True
downspeed = 0
def updating():
global downspeed
while can_run:
downspeed = downspeed+1
time.sleep(0.1) # Allow taskswitches
def main():
while can_run:
print(downspeed)
time.sleep(1) # Allow taskswitches
u = threading.Thread(name='background', target=updating)
m = threading.Thread(name='foreground', target=main)
u.start()
m.start()
time.sleep(10) # Allow time for the threads to do what they want
can_run = False
print('Done')
u.join()
m.join()
There are no problems sharing variables in python because of the GIL. Although this only makes changes atomic.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want to create a thread which runs a list of functions which are passed to it, the list can be updated real time so a function in the list could be switched out.
What is the correct way to do this? How would I create a variable list of functions in Python?
Here is example:
Code
class a:
def f1(self, i):
print(f'function 1 executed, index={i}')
def f2(i):
print(f'function 2 executed, index={i}')
def f3(i):
print(f'function 3 executed, index={i}')
object_of_a = a()
function_list = [object_of_a.f1, f2]
for arg, fn in enumerate(function_list):
fn(arg)
function_list[1] = f3
for arg, fn in enumerate(function_list):
fn(arg)
Output
function 1 executed, index=0
function 2 executed, index=1
function 1 executed, index=0
function 3 executed, index=1
Here is an example with a list of arguments:
Code
def f1(i):
print(f'function 1 executed, arg={i}')
def f2(i):
print(f'function 2 executed, arg={i}')
def f3(i):
print(f'function 3 executed, arg={i}')
function_list = [f1, f2]
argument_list = ['arg1', 'arg2']
for arg, fn in zip(argument_list, function_list):
fn(arg)
function_list[1] = f3
for arg, fn in zip(argument_list, function_list):
fn(arg)
Output
function 1 executed, arg=arg1
function 2 executed, arg=arg2
function 1 executed, arg=arg1
function 3 executed, arg=arg2
Functions can be stored in lists just like variables and data structures can be. When adding them to a list, be sure to only use the name of the function and to exclude the () so that it adds the function itself, rather than the output of the function.
There are a couple ways you could make it so that the list can be updated in real time. As long as the thread is able to look up externally accessible data, it will work. For two examples, the thread could access class data or data stored in a file.
Here's some sample code for a class data example:
import threading
import time
class Obj:
def __init__(self):
self.functions = []
def call_functions(self):
for function in self.functions:
function()
time.sleep(5)
def add_function(self, function):
self.functions.append(function)
def a():
print("a")
def b():
print("b")
def c():
print("c")
if __name__ == "__main__":
obj = Obj()
obj.add_function(a)
obj.add_function(b)
thread = threading.Thread(target=obj.call_functions)
thread.start()
obj.add_function(c)
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 1 year ago.
Improve this question
Somehow this is frying my brain, i dont know how to get the function to start again after they are done. The goal is to run them at the same time and when theyre finished they should start again:
if __name__ == '__main__':
current_task += 1
Thread(target = main).start()
current_task += 1
Thread(target = main).start()
pass
You could use a while loop within main:
import threading
import time
def main():
while 1:
print("starting")
time.sleep(2)
print("done")
if __name__ == '__main__':
threading.Thread(target=main).start()
Out:
starting
done
starting
done
starting
...
You could start a new thread at the end of your main-method:
def main():
# .. do some stuff ..
Thread(target=main).start()
if __name__ == '__main__':
current_task += 1
Thread(target = main).start()
current_task += 1
Thread(target = main).start()
pass
This way, both threads spawn a new thread with a new execution once they are done.
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 2 years ago.
Improve this question
What I was wondering is if it's possible to put a timer in my program so that like every 1 min. the program will update a list box with data?
class App():
def __init__(self):
self.root = tk.Tk()
self.label = Label(text="")
self.label.pack()
self.update_clock()
self.root.mainloop()
def update_clock(self):
now = time.strftime("%H:%M:%S")
self.label.configure(text=now)
# Put Arrivals in box===============================================================
arrivallb.delete(0, END)
now = dt.datetime.now()
dte = now.strftime("%m-%d-%Y")
conn = sqlite3.connect('reservation.db')
c = conn.cursor()
c.execute("SELECT * FROM reserve")
records = c.fetchall()
for record in records:
if record[22] != "*":
if record[8] == dte:
arrivallb.insert(0, str(record[13]) + " " + record[0] + ", " + record[1])
self.root.after(10000, self.update_clock)
app=App()
I figured it out. Below is the code that updates my list box. Thanks everyone for your input.
class App():
def __init__(self):
self.root = tk.Tk()
self.label = Label(text="")
self.label.pack()
self.update_clock()
self.root.mainloop()
def update_clock(self):
now = time.strftime("%H:%M:%S")
self.label.configure(text=now)
# Put Arrivals in box===============================================================
arrivallb.delete(0, END)
now = dt.datetime.now()
dte = now.strftime("%m-%d-%Y")
conn = sqlite3.connect('reservation.db')
c = conn.cursor()
c.execute("SELECT * FROM reserve")
records = c.fetchall()
for record in records:
if record[22] != "*":
if record[8] == dte:
arrivallb.insert(0, str(record[13]) + " " + record[0] + ", " + record[1])
self.root.after(10000, self.update_clock)
app=App()
Python has a library called ascynio, which is part of the standard library. You can have two or more separate processes (coroutines) running with a long sleep in one of them. Here's a mock program that may or may not work but has the general idea in mind.
Warning: this code hasn't been tested
import asyncio
async def wait(): # you can try and use a while true here
await asyncio.sleep(60)
updateListBox()
return
async def otherStuff():
# code here: make sure it terminates at some point, unless you try the while true method from above
return
async def main():
while True:
await asyncio.gather(
otherStuff(),
wait()
)
asyncio.run(main())
Here's the asyncio documentation https://docs.python.org/3/library/asyncio-task.html
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 4 years ago.
Improve this question
import time
def profile(function):
def wrapper(*args):
start_time = time.time()
function(*args)
end_time = time.time()
function.time_taken = end_time-start_time
return exec_time
return wrapper
"""
#profile
def calsqr(a,b):
return a**b
"""
#profile
def expensive_operation():
import time
time.sleep(3)
return 1
print(expensive_operation.time_taken)
assert expensive_operation() == 1
You need to assign time_taken to wrapper function, and first call it in order to be able to access time_taken variable
import time
def profile(function):
def wrapper(*args, **kwargs):
start_time = time.time()
ret_value = function(*args, **kwargs)
end_time = time.time()
wrapper.time_taken = end_time-start_time
return ret_value
return wrapper
"""
#profile
def calsqr(a,b):
return a**b
"""
#profile
def expensive_operation():
import time
time.sleep(3)
return 1
assert expensive_operation() == 1
print(expensive_operation.time_taken)