Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
How can I add 1 to a variable every 2 minutes it until reaches 100.
The program will start the number from 0 and it will add every 1 number in every 2 minutes until it reaches 100.
2 min later
0/100 ------> 1/100
Use sleep function from time module
from time import sleep
i = 0
while i <= 100:
sleep(120)
i += 1
I used sleep!
from time import sleep
for i in range(100):
sleep(120)
# print(i)
If you need to make a progressbar, you can also check tqdm.
from tqdm import tqdm
import time
for _ in tqdm(range(100)):
time.sleep(120)
One line solution:
from time import sleep
for t in range(100): time.sleep(120)
I believe all solutions presented so far are thread locking??
import asyncio, time
async def waitT(tWait, count):
print(count)
while count < 100: #The 100 could be passed as a param to make it more generic
await asyncio.sleep(tWait)
count = count + 1
print(count)
return
async def myOtherFoo():
#Do stuff in here
print("aaa")
await asyncio.sleep(2)
print("test that its working")
return
async def main(count):
asyncio.gather(myOtherFoo(), waitT(120, count)) #Obviously tweak 120 to whatever interval in seconds you want
return
if __name__ == "__main__":
count = 0
asyncio.create_task(main(count))
A simple, and hopefully readable, async solution. Doesn't check for running loops etc - but should open you up to a range of possibilities for acting between each update in your counter.
Related
This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 5 days ago.
I'm very new to python, and I'm trying to make a sort of idle game. I'm having a little bit of trouble optimizing a function I wrote that flashes "ON" and then "OFF" every time a second passes.
While it works fine, it checks to see if a second has passed so many times that it peaks my CPU. The code is below:
import time
def timer():
oldtime = int(time.time())
#grabs the time on initiation
while True:
if oldtime < int(time.time()):
return 'ON'
#flashes on
return 'OFF'
#makes everything that checks if it's on only proc once
oldtime += int(time.time()) - oldtime
#makes oldtime advance one second ahead of time.time(),
#even if more than one second passes at a time
timer()
while timer() == "ON":
print('lorem ipsum')
#output: lorem ipsum every second and a peaking CPU
How would one go about optimizing something like this?
Here I have written a while loop that calls a function that will check the previous state of a variable and depending on whether it was ON or OFF it will sleep for 1 second and change to the other state.
import time
def repeat():
isOn = True
if(isOn):
time.sleep(1)
isOn = False
return 'OFF'
if(isOn != True):
time.sleep(1)
isOn = True
return 'ON'
while True:
#You could always take the return value of repeat() to do something else
#in your code
repeat()
I'm not sure if this is actually what you want as I feel like you are likely looking to do "something else" in the pause.
However, looking at your code, I think this will give you the result you are currently working towards. The key to not using up resources is to sleep()
import time
def timer():
time.sleep(1)
return ["On ", "Off"][int(time.time() % 2)]
while True:
print(timer(), end="\r", flush=True)
import time
i = 1
def sendData(x):
time.sleep(5)
print("delayed data: ", x)
while (1):
print(i)
sendData(i)
i += 1
time.sleep(0.5)
What I want is to print a value every 5 seconds while the infinite loop runs.
so I can see the values printing very .5 seconds and another value being printed every 5 seconds.
At the moment, the loop still gets delayed because of the time.sleep(5) in the helper function. Any help is appreciated. Thank you.
You can achieve your goal using the threading library. It allows you to run code in the "background" while your main code runs alongside it.
Here's an example of how to run the sendData function in the background with the main loop executing concurrently. Notice that I modified sendData to use the global variable i instead of receiving it as a parameter to allow the main loop to update i.
import threading
import time
i = 1
def sendData():
while True:
time.sleep(5)
print("delayed data: ", i)
thread = threading.Thread(target=sendData)
thread.start()
while (1):
print(i)
i += 1
time.sleep(0.5)
You can read more about threading and sharing variables when using threading.
You could achieve this with an asynchronous approach or use multi-[threading|procesiing]
Your approach is blocking the execution as it runs step by step.
Choosing the approach depends on the task that you want to perform in the sendData method, but from the name, I could suggest asyncio should work just fine.
import asyncio
async def send_data(x):
await asyncio.sleep(5) # Could be network request as well
print("delayed data: ", x)
async def main():
i = 1
while True:
print(i)
# Create non blocking task (run in background)
asyncio.create_task(send_data(i))
i += 1
await asyncio.sleep(0.5)
if __name__ == '__main__':
asyncio.run(main())
This code may help you. But, you need to modify them as you want
# importing module
import time
# running loop from 0 to 4
for i in range(0,5):
# printing numbers
print("delayed data: ", i)
# adding 0.5 seconds time delay
time.sleep(0.5)
the output print every 0.5 sec like this:
delayed data: 0
delayed data: 1
delayed data: 2
delayed data: 3
delayed data: 4
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 last year.
Improve this question
I'm making a dodging game in Python where I want the score to increase by 1 every second, but the problem is that I don't know how. It would be nice to find a solution where I don't have to change too much of my code.
Can someone please help?
As you iterate through the game loop, you can check the current time with the time library. You can then check if it has been a second since the last time you awarded a point.
It might look something like this:
import time
points = 0
currentTime = time.time()
previousPointAwardedTime = currentTime
while gameRunning == True:
...
currentTime = time.time()
if (currentTime - previousPointAwardedTime) >= 1:
points += 1
previousPointAwardedTime = currentTime
you can try using asyncio
import asyncio
score = 0 # starting game with a score of zero
async def s():
global score
score += 1 #increasing score by 1
await asyncio.sleep(1) #waiting for 1 second
while True: #while game is running
asyncio.run(s()) #calling function
print(score) #printing score
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 last year.
Improve this question
I have recently heard some things about parallel programming and I know basically nothing about it but will read up on it. But as a start, is it possible to run for instance this code:
for i in range(1000):
print('Process1:', i)
for j in range(1000):
print('Process2:', j)
in parallel? This case is just a toy example but it would help the understanding of the "potential" of parallel programming.
And, if that code can be ran in parallell, will it print out output from both loops in parallell in the following manner:
Process1: 0
Process2: 0
Process1: 1
.
.
.
or what?
Since you are a beginner, the same with threading below:
(Note that the output is not controlled in any way and might mix up!)
import threading
def f1():
for i in range(1000):
print('Process1:', i)
def f2():
for j in range(1000):
print('Process2:', j)
t1=threading.Thread(target=f1)
t2=threading.Thread(target=f2)
t1.start()
t2.start()
Short anser is yes, and how the output will look depends on which method you use.
For example if you want to use concurrent.futures, you can print the output as it is performed inside the function, and order will be scrambled.
If you instead want to access return values, you can chose if you want to access them as they are completed, in whichever order they happen to finish, or you can use the "map" function to retrieve them in the expected order.
import concurrent.futures
def test_function(arguments: tuple):
test_value, function = arguments
"""Print the test value 1000 times"""
for i in range(0, 1000):
print(f"Function {function}, {test_value}, iteration {i}")
return test_value
def main():
"""Main function"""
# Context manager for parallel tasks
with concurrent.futures.ThreadPoolExecutor() as executor:
# Submit example. Executes the function calls asynchronously
result = [executor.submit(test_function, (i, "submit")) for i in range(1, 21)]
# Map example.
# Takes an iterable as argument that will execute the function once for each item
result_2 = executor.map(test_function, [(i, "map") for i in range(1, 21)])
for future in concurrent.futures.as_completed(result):
print(f"Submit: Process {future.result()} completed")
for future in result_2:
print(f"Map: Process {future} completed")
if __name__ == '__main__':
main()
This question already has answers here:
How do I get my program to sleep for 50 milliseconds?
(6 answers)
Closed 8 years ago.
I have the following for loop:
for user_id in new_followers:
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
To avoid API limitations, I want to pause the loop for 600 seconds each time 100 direct messages are sent.
What's the best way to do it?
You can try this:
for i, user_id in enumerate(new_followers):
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
if (i+1)%100 == 0:
time.sleep(x) # here x in milisecond
You could do this:
import time
count = 0
for user_id in new_followers:
count +=1
if count == 100:
count = 0
time.sleep(600)
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
Use a counter within the loop, counting up to 100 messages.
When counter == 100, use
from time import sleep
sleep(AMOUNT_OF_TIME)
You can use:
import time
and then
time.sleep(seconds)
to sleep. You can use floats for smaller time than a second.
One thing to note, people will likely hate you if you do this.