I am making a Discord bot which allows you to create a poll. The user can put as an argument how long the poll will be. So I want to refresh every 5s or 10s (or maybe more) the message with the poll editing how much time the user has left. I want to implement a countdown from 3600 seconds for example, and every 5s or 10s execute a function which will edit the message until the time goes to 0. Everything on the bot side I have it under control and more or less I know how to implement it.
So, what I thought is making an interval and stop when the current time is equal to time when it started + duration of the poll. So I can use the rx.interval() for creating the observable and use an operator like .take_while().
This is my code:
import time
import rx
print(rx.__version__) # 3.1.1
started_at = time.time() # Time in seconds
end_at = started_at + 3600 # One hour after
source = rx.interval(5).take_while(time.time() < end_at)
But I get AttributeError: 'Observable' object has no attribute 'take_while'.
I think I should put it in a pipe or something like this:
from rx import operators as op
sub = source.pipe(op.take_while(time.time() < end_at))
But I get TypeError: 'bool' object is not callable
How can I use take_while? Thank you!
You should pipe the source and then subscribe. You have to use operators inside of the pipe() method that the Observable has (https://rxpy.readthedocs.io/en/latest/reference_observable.html#rx.Observable.pipe)
The code should look something like this
import time
import rx
from rx import operators as op
print(rx.__version__) # 3.1.1
started_at = time.time() # Time in seconds
end_at = started_at + 3600 # One hour after
ob = rx.interval(5)
sub = ob.pipe(op.take_while(lambda _: time.time() < end_at))
sub.subscribe(lambda i: print(i))
Related
How do you create a timer in python? My project is a speed typing test and the timer is there to time the length it takes the user to type. The first task the user types is the alphabet, as fast as they can and then the second task is to type as quickly as possible again for a group of words in set in a random order
The time module
The time module allows the user to directly get the time, in seconds, since 1970 (See: https://docs.python.org/3/library/time.html). This means that we can subtract the time before from time after to see how long it has been, namely how long it took the user to finish the typing test. From there, it is as easy as printing the result. You can round the time using int to get a purely seconds result without milliseconds.
The code
# Import the time library
import time
# Calculate the start time
start = time.time()
# Code here
# Calculate the end time and time taken
end = time.time()
length = start - end
# Show the results : this can be altered however you like
print("It took", start-end, "seconds!")
You can use the build in time libary:
import time
strToType="The cat is catching a mouse."
start_time = time.perf_counter()
print("Type: '"+strToType+"'.")
typedstring=input()
if typedstring==strToType:
end_time = time.perf_counter()
run_time = end_time - start_time
print("You typed '"+strToType+"' in "+str(run_time)+" seconds.")
This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed 1 year ago.
I have a function which keeps capturing the data from live stream. I want to run this code for 30 minutes.
You can easily achieve this using the datetime module with a while loop:
from datetime import datetime, timedelta
start_time = datetime.now()
while datetime.now() - start_time <= timedelta(minutes=30):
... your code ...
By doing it like this, your code will get repeated until the difference between the current time and the start time is less than or equal to 30 minutes, meaning it will stop once it will reach 30 minutes.
A possible way could be to run the function in a separate process and make it terminates when the parent tells it to (sets the quit event):
import time
import multiprocessing as mp
def your_function(args, quit):
while not quit.is_set():
... # your code
return
if __name__ == '__main__':
quit = mp.Event()
p = mp.Process(target=your_function, args=(args, quit))
p.start()
time.sleep(1800) # in sec, half an hour
quit.set()
The advantage of using mltiprocessing is that you can do other stuff while the other process listens to the call.
I have a Django web app which is used by embedded systems to upload regular data, currently every 2 minutes, to the server where Django just pops it into a database.
I'd like to create an alert system where by if there's no data uploaded from the remote system in a time period, say 10 minutes for example, I raise an alarm on the server, via email or something.
In other programming languages/environments I'd create a 10 minute timer to execute a function in 10 minutes, but every time data is uploaded I'd restart the timer. Thus hopefully the timer would never expire and the expiry function would never get called.
I might well have missed something obvious but if there is something I have missed it. This just does not seem possible in Python. Have I missed something?
At present looks like I need an external daemon monitoring the database :-(
You could use the time module for this:
import time
def didEventHappen():
# insert appropriate logic here to check
# for what you want to check for every 10 minutes
value = True # this is just a placeholder so the code runs
return value
def notifyServer():
print("Hello server, the event happened")
start = time.clock()
delay = 10 * 60 # 10 minutes, converted to seconds
while True:
interval = time.clock() - start
eventHappened = False
if interval >= delay:
eventHappened = didEventHappen()
start = time.clock() # reset the timer
if eventHappened:
notifyServer()
else:
print("event did not happen")
Alternatively, you could use the sched module.
I would like to implement a cron-like behaviour with my twisted application.
I want to trigger a periodic call (let's say every week) but running at a precise time only, not when i start my application.
My use case is the following:
my python application is started at any time in the week. I want the calls to be performed every monday at 8am.
But I don't want to perorm active waiting (using a time.sleep()), i would like to use callLater to trigger the call next monday and then start a looping call from that date.
any idea/advice?
thanks,
J.
If you are absolutely in love with cron-style specifiers, you could also consider using parse-crontab
Then your code looks basically like:
from crontab import CronTab
monday_morning = CronTab("0 8 * * 1")
def do_something():
reactor.callLater(monday_morning.next(), do_something)
# do whatever you want!
reactor.callLater(monday_morning.next(), do_something)
reactor.run()
If I understood your question correctly you are thinking of first time execution of a scheduled task and how to supply initial start time for the app. If this is a case, you just need to calculate timedelta value in seconds to be passed to callLater.
import datetime
from twisted.internet import reactor
def cron_entry():
full_weekseconds = 7*24*60*60
print "I was called at a specified time, now you can add looping task with a full weekseconds frequency"
def get_seconds_till_next_event(isoweekday,hour,minute,second):
now = datetime.datetime.now()
full_weekseconds = 7*24*60*60
schedule_weekseconds = ((((isoweekday*24)+hour)*60+minute)*60+second)
now_weekseconds=((((now.isoweekday()*24)+now.hour)*60+now.minute)*60+now.second)
if schedule_weekseconds > now_weekseconds:
return schedule_weekseconds - now_weekseconds
else:
return now_weekseconds - schedule_weekseconds + full_weekseconds
initial_execution_timedelta = get_seconds_till_next_event(3,2,25,1)
"""
This gets a delta in seconds between now and next Wednesday -3, 02 hours, 25 minutes and 01 second
"""
reactor.callLater(initial_execution_timedelta,cron_entry)
reactor.run()
Through a python program, sending a command to specific device and that device is responding on the behalf of the command. Now I have to calculate timing between send and receive (means how much time taking to response of the command ).
Ex.
device ip - 10.0.0.10
transmitting 'L004' command through our local system to 10.0.10.
Receving 'L' response from 10.0.0.10.
So now I have to calculate time difference between start time and end time.
Please provide an API through that I can calculate.
import time
t1 = time.time()
# some time-demanding operations
t2 = time.time()
print "operation took around {0} seconds to complete".format(t2 - t1)
time.time() returns the current unix timestamp as a float number. Store this number at given points of your code and calculate the difference. You will get the time difference in seconds (and fractions).
The timeit standard module makes it easy to do this kind of task.
Just Use "timeit" module. It works with both Python 2 And Python 3
import timeit
start = timeit.default_timer()
#ALL THE PROGRAM STATEMETNS
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+execution_time) #It returns time in sec
It returns in Seconds and you can have your Execution Time. Simple but you should write these in Main Function which starts program execution. If you want to get the Execution time even when you get error then take your parameter "Start" to it and calculate there like
`def sample_function(start,**kwargs):
try:
#your statements
Except:
#Except Statements
stop = timeit.default_timer()
execution_time = stop - start