how to shutdown/stop scheduler after a specific time - python

I am creating a job which should run after every 10 seconds for next 2 hours, how can I do that?
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
#sched.scheduled_job('interval', seconds=10)
def timed_job():
print('This job is run every 10 seconds.')
sched.start()
How can I stop this scheduled job to stop after 2 hours?

You could use the time built-in module. You can do start_time = time.time() to get the start time. Then do a boolean test before running your code of if time.time()-start_time < 7200 and then your code. Otherwise it would cancel. Then your code will continue to run until 7200 seconds(2 hours) has passed.

import time
def hello():
print("hello-world ")
start_time = time.time()
while(time.time() - start_time < 20):
hello()
time.sleep(5)

Related

Break a while loop with the sleep function inside after a certain period of time

How can i stop a while loop after a certain time in which the sleep function is used. The condition inside a while loop does not work correctly because the sleep function pauses the execution of the code.
In this case i have delay for 40 seconds before a while loop stops:
# timeout for 10 minutes
timeout = time.time() + 60*10
while True:
if time.time() >= timeout:
break
# do something
sleep(20)
# do something
sleep(20)
you may use the code below.
import datetime
import time
timeout = datetime.datetime.now() + datetime.timedelta(seconds=20) # define here!
while True:
now = datetime.datetime.now()
if now >= timeout:
print('time is up !')
break
else:
print('do something')
time.sleep(5) # define here!
continue
Looks like you need a variable sleep duration.
Something like this:
from time import time, sleep
timeout = time() + 10 * 60
while time() < timeout:
# do some work
sleep_duration = min(20, timeout - time())
sleep(sleep_duration)
This means that the sleep will be at most 20s
Probably, the fastest solution will be to set the certain amount of sleep.
timeout = time.time() + 60*10
while time.time() < timeout:
# do something
# added clipping negative numbers too
time_left = max(0,min(20, timeout - time.time()))
sleep(time_left)
if time_left == 0:
break
time_left = max(0,min(20, timeout - time.time()))
# do something
sleep(time_left)
Not the most elegant solution. But should work

milliseconds countdown timer in python

there was a lot of models available here of a countdown timer but almost all of them does not have a millisecond value
the model im using :
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Fire in the hole!!')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
countdown(int(t))
i understand the divmod() method but i still find it difficult to understand how to extract milliseconds from this
Your code does not keep track of any milliseconds. You sleep(1) - which should sleep at least 1000ms (maybe more - see here - it depends on what is going on on your PC elsewise).
To display any ms you need to capture the current time somehow:
from datetime import datetime, timedelta
import time
def countdown(seconds):
started = datetime.now()
ended = started + timedelta(seconds=seconds)
while datetime.now() < ended:
print(f"Waiting for {ended-datetime.now()}", flush=True)
time.sleep(1)
now = datetime.now()
if now > ended:
print(f'Sorry, I overslept: {now-ended}')
print('Fire in the hole!!')
# input time in seconds
t ="4"
# function call
countdown(int(t))
To get:
Waiting for 0:00:04
Waiting for 0:00:02.995686
Waiting for 0:00:01.995361
Waiting for 0:00:00.980077
Sorry, I overslept: 0:00:00.020248
Fire in the hole!!
You can format the timedelta to your conveniece - more solutions to that f.e. here: Formatting timedelta objects.
Sleeping for a calculated time like
while datetime.now() < ended:
remainder = ended-datetime.now()
print(f"Waiting for {remainder}", flush=True)
time.sleep(min(1, ( ended-datetime.now()).total_seconds()))
could try to minimize your over-sleep time on the last loop. You could also try to do this for every loop by calculating what you need to sleep if need better 1s precision.
But in the end your loops may still be off due to factors you can not influence.
fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f")
fulldate = fulldate + datetime.timedelta(milliseconds=500)
This should solve your problem,
https://docs.python.org/2/library/datetime.html#timedelta-objects

How we can stop a program at certain time in a day#15:30pm everyday…?(It's running every 1 minute)

Anyone help me to get code for below conditions...
I would like to run job1 and job2 for every 2 and 3 seconds,
job1 and job2 should start#9:30am in a day..and should stop#17:30pm...!
job3 #17:31pm daily once only..
import schedule
import time
def job1():
print("I'm working...")
def job2():
print("I'm not working...")
def job3():
print("I'll not work...")
schedule.every(2).seconds.do(job1) #For Every 2 seconds
schedule.every(5).seconds.do(job2) #For Every 3 Seconds
schedule.every().day.at("17:28").do(job3) #Once in a day
while True:
schedule.run_pending()
time.sleep(1)
You can wrap this into a function and start it in a given time with a scheduler
schedule.every(2).seconds.do(job1) #For Every 2 seconds
schedule.every(5).seconds.do(job2) #For Every 3 Seconds
And you could do the same with canceling the job when you want. So you will have 2 extra job which starts and stops the other jobs.
Probably not the nicest way of doing this, but something like this should work. (You obviously can extend the if statement to incorporate only weekdays/exclude holidays etc.)
import datetime
import time
def job_a():
print('a')
def job_b():
print('b')
def job_3():
print('3')
start_a = datetime.datetime.now()
wait_time_a = 2
start_b = datetime.datetime.now()
wait_time_b = 5
start_time = 9.30
end_time = 17.31
do_job_3 = False
while True:
while datetime.datetime.now().hour + datetime.datetime.now().minute/100. > start_time \
and datetime.datetime.now().hour + datetime.datetime.now().minute/100. < end_time:
do_job_3 = True
if (datetime.datetime.now() - start_a).seconds > wait_time_a:
job_a()
start_a += datetime.timedelta(seconds=wait_time_a)
if (datetime.datetime.now() - start_b).seconds > wait_time_b:
job_b()
start_b += datetime.timedelta(seconds=wait_time_b)
time.sleep(1)
if do_job_3:
do_job_3 = False
job_3()
time.sleep(1)

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

python timer in minutes

I am trying to run the below code. It fails to run for 5 minutes, can you please let me know what the issue is here. I am trying to run this in background by saving as .pyw and alert me after finishing 1 hours, as per what is passed in timer arguments.
import time
import ctypes
def timer(minutes):
seconds = minutes * 60
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
time.sleep(1)
timer(5) #would want enter in hours not in seconds
ctypes.windll.user32.MessageBoxA(0,"DoneToday", "Dones", 0)
Your timer() function is infinitely looping.
After your while elapsed < seconds: loop, two lines down, you've put timer(5). So that just calls itself again, and again, again...
Once you remove this line, it will work as expected:
timer(5) #would want enter in hours not in seconds
And as #vermillon mentioned, any reason you're not just doing time.sleep(minutes * 60)? I'm assuming you plan to do something else in that loop, other than just counting time.
Edit: For the OP to see running code
>>> def timer(minutes):
... seconds = minutes * 60
... start = time.time()
... time.clock()
... elapsed = 0
... while elapsed < seconds:
... elapsed = time.time() - start
... time.sleep(1)
... ctypes.windll.user32.MessageBoxA(0,"DoneToday", "Dones", 0)
... print 'also printing Done so you can see it'
...
>>> timer(0.1)
also printing Done so you can see it
>>>
If you want a timer that shows minutes and seconds remaining, then here's the snippet for you:
import time
import sys
def run_timer(seconds):
for remaining in range(seconds, 0, -1):
sys.stdout.write("\r")
minutes = 0
seconds = remaining
if remaining > 60:
minutes = int(seconds/60)
seconds = int(seconds%60)
else:
seconds = remaining
sys.stdout.write("{:2d} minutes {:2d} seconds remaining.".format(minutes,seconds))
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("Timer complete")
run_timer(120)

Categories

Resources