Python - schedule with random delay - python

I'am learning python by doing little projects on my own. I'am struggling to schedule scripts with random delay in a range.
In the code below, the delay is random but always the same ... I Really need help.
import schedule
import time
import random
import datetime
def job():
t = datetime.datetime.now().replace(microsecond=0)
print(str(t) + " hello")
i = 0
while i < 10:
delay = random.randrange(1, 5)
schedule.every(delay).seconds.do(job)
i += 1
while True:
schedule.run_pending()
time.sleep(1)

Think through your loops. Your first while loop creates a second infinite while loop. So you never continue to the function that would create a new delay.
import schedule
import time
import random
import datetime
def job():
t = datetime.datetime.now().replace(microsecond=0)
print(str(t) + " hello")
i = 0
for i in range(10):
delay = random.randrange(1, 5)
print(delay)
schedule.every(delay).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(.01)

Related

Using two different functions at the same time in python

import time
import random
def timer():
correct = 1
x = 0
while correct != 2:
time.sleep(0.1)
x = x + 0.1
def round1():
numb = random.randint(1, 100)
print(numb)
timer()
ans = input(">")
if ans == numb:
correct = 2
x = round(x)
print("you did that in", x ,"seconds!")
round1()
I was trying to get both functions to run together (have the game playing and the timer going in the background) but as soon as the timer started it would let me continue the game.
In the given program, I have created two different functions that will work at the same time. I have used threading to create thread of functions and sleep to limit the printing speed. In similar manner you can use game and timer function together.
from threading import Thread
from time import sleep
#sleep is used in functions to delay the print
#the below functions has infinite loop that will run together
#defining functions
def func1():
for x in range(20):
sleep(1)
print("This is function 1.")
def func2():
for x in range(10):
sleep(2)
print("This is function 2.")
#creating thread
thread1=Thread(target=func1)
thread2=Thread(target=func2)
#running thread
thread1.start()
thread2.start()

Python command repeats same number in command(im learning python)

I tried to make a twitter bot to print random number but it print the same number while testing the command
import tweepy
import random
import time
import threading
import schedule
start = time.perf_counter()
while time.perf_counter() - start < 2:
random_number = random.randint(0,10000)
time.sleep(1.0)
def job():
print(random_number)
# run the function job() every 2 seconds
schedule.every(2).seconds.do(job)
while True:
schedule.run_pending()
What should I do in order to have random numbers?
Your first block defines the random_number, which is then fixed.
You should compute the random number in your job
import random
import time
import threading
import schedule
def job():
print(random.randint(0,10000))
# run the function job() every 2 seconds
schedule.every(2).seconds.do(job)
while True:
schedule.run_pending()

Python datetime does not sync with system time

i'd like to know how to sync datetime with system time in real time. what i mean is the code always prints the same hour same minute and same seconds if i loop the code. this is my code
from datetime import datetime
import os
from time import sleep
def clear():
os.system('cls')
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
while True:
time = print("Current Time =", current_time)
sleep(1)
clear()
i need help for this thx!
You are currently creating the date-time object only once with the line. This means the time is only looked up once and then that value is stored in the variable.
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
All you need to do is move those two lines into your loop. That way, the time is looked up on each loop iteration and you get new values. The modified code:
from datetime import datetime
import os
from time import sleep
def clear():
os.system('cls')
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
time = print("Current Time =", current_time)
sleep(1)
clear()
Thanks for the answer! i also modify the code a little bit to make it a little bit better
from datetime import datetime
from time import sleep
while True:
now=datetime.now()
current_time=now.strftime("%H:%M:%S")
time=print("Current Time : ", current_time, end=\r)
sleep(1)

Execute specific tasks for each specific time and wait for its time (Python)

I would like to create a different task for every specific time and it will wait for the time and continue it day over day.
Below are my code but it only for one task.
import time, datetime
time_now = time.localtime(time.time())
now = []
now = time.strftime("%H:%M:%S", time_now)
value = []
value = time.strftime("15:00:00")
print(now)
print(value)
while value == now:
time.sleep(1)
print("\nSuccess")
I have implemented in my project and it's working properly. Please have a look on below code.
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.http import condition
import time
#condition(etag_func=None)
def stream(request):
resp = StreamingHttpResponse(stream_response_generator(request))
return resp
def stream_response_generator(request):
start = time.time()
end = start + 60
while start < end:
#Here you can add your method
print ("This is test") # will print after 60 secound after frist executing of time
time.sleep(2) # sleep time added

Q : Python time

I would like to use ·time()· to launch an event. An example would be to print("test") for 3 seconds. For that I did this:
from time import time, sleep
from random import random
t = time()
n = 3
print(n, time() - t)
for i in range(100):
sleep(0.04)
print(time() - t)
if time() - t > n:
print("test")
break
and it works! But in my game, in a while loop, it does not work... Why not?
If I've understood correctly, it seems you don't know how to run a simple gameloop and run some test code after 3 seconds, here's some naive approach:
from time import time, sleep
from random import random
start_time = time()
n = 3
while True:
elapsed_time = time() - start_time
sleep(0.04)
print(elapsed_time)
if elapsed_time > n:
print("test")
break
if you want to achieve something else during the 3 second delay period, rather than just going round a while loop, try using a time-delayed thread. For example, the following
import threading
import time
def afterThreeSec():
print("test")
return
t1 = threading.Timer(3, afterThreeSec)
t1.setName('t1')
t1.start()
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
gives the output:
main
main
main
test
main
main

Categories

Resources