I'm trying to place a call 'on hold' in asterisk using a python AGI script, the function will check if the person is available, when he is asterisk will dial the person if he is not the script should wait 10 seconds before checking availabilty again and dial when the person is available. However I ran into a small problem, using the time.sleep(10) function hangs up the call when a person is not available, I expect this is because the thread the script runs on will sleep and asterisk thinks the script is done running and hangs up the call. Removing the time.sleep() gives me what I want without the time interval.
agi = AGI()
agi.verbose("python agi started")
place_call_on_hold("SIP/6001")
def place_call_on_hold(s):
agi.verbose("entered place_call_on_hold function")
while True:
status = agi.get_variable('DEVICE_STATE(%(redirect)s)'%{'redirect':s})
agi.verbose(status)
if status == 'NOT_INUSE':
agi.verbose("Info: place_call_on_hold: calling the number")
agi.appexec("Dial",s)
else:
agi.verbose("Info: place_call_on_hold: sleeping for 10 sec")
time.sleep(10)
Is there a way to wait 10 seconds without using the sleep() function or how can I make sure the call won't end before the time.sleep wakes back up?
why not try time difference before condition and after condition something like this
import time
start = time.time()
end = time.time()
while (end-start) < 10:
end = time.time()
print(start, end, end-start)
I fixed my problem by just calling the Asterisk Wait(10) function instead of time.sleep(10).
Related
I have a command in a line (Fit.perform() from import xspec, but never mind because the question is general and can be applicated also for other python commands) that takes a while to finish.
I simple want to know the time of execution while the command is running, so when it has not finished its execution yet.
This is necessary if I want to stop the command during its execution, for example because it is taking too much time to end.
So, I need something like this:
if **you_are_taking_so_much_time**:
do_something_else
It is not possible to use methods like time or timeit because they calculate the time only at the end of execution of a command and not while it is running.
Is it possible?
I'm using python 2.7 on MacOS.
You will have to use a monitor thread:
import threading
import time
done = False
def longfun():
global done
print("This will take some time.")
time.sleep(60)
done = True
def monitor():
global done
timeout = 10
print("Wait until timeout.")
while not done and timeout > 0:
time.sleep(1)
timeout -= 1
lt = threading.Thread(target=longfun)
lt.start()
mt = threading.Thread(target=monitor)
mt.start()
mt.join()
if done == False:
print("Long thread not done yet. Do something else.")
lt.join()
Note that this does wait until the 'long' thread is finished. You do not mention you want to stop the long running operation. If you do, you will have to correctly implement it in a thread, including start/stop/progress functionality (usually this works with a while loop that uses a running bit to see if it should continue.
like this:
import time,thread
def test_me(hargs):
func,args,timeout = hargs
start_time = time.time()
thread.start_newthread(func,args)
while True :
if My_expected_value:#where store this ?
print "well done !"
break
elif time.time() > (timeout + start_time) :
print "oh! to late, sorry !"
break
time.sleep(timeout/100)
thread.start_newthread(test_me,((func,args,timeout),))
important warnings : need use thread for Non-freezing application, got 3 thread for this: 1-main app, 2-test_me, 3- Your function(func)
Don't forget adding external variable to your function (for killing your function thread)
I am trying to run a specific function in my python file. However, when I run the method with the timer that calls said function, it executes everything that it's supposed to, but then exits the job after the first time. I need it to continue to run the function after the specified time.
This is the function that contains the timer:
def executor(file):
x = datetime.today()
y = x.replace(day=x.day, hour=x.hour, minute=x.minute, second=x.second+10, microsecond=0)
delta_t = y-x
secs = delta_t.seconds+1
t = Timer(secs, parse_file, [file])
t.start()
The function that I am trying to call, is parse_file(file_name).
I am passing in the file_name when calling the executor function.
You haven't given enough detail of what your actual issue is, what code do you want to run more than once? Can you show the code that actually calls this function?
When you call start, the main thread will continue executing from that spot, while the task you scheduled will call the parse_file method at the specified time, and exit once complete. It sounds to me like you don't have anything that is keeping your main thread alive (that is, you don't have any more code after you call the executor).
Here is a small example showing how you can use the Timer to execute tasks while the main thread is still working. You can keep typing in input, and the print statement will show you all the threads that completed since the last time you typed an input.
from threading import Timer
import sys
def scheduled_task(arg):
print("\ntask complete arg %s!\n"%(arg))
def run_scheduled_task(arg):
timer = Timer(10, scheduled_task, [arg])
timer.start()
done = False
while not done:
user_input = input("Give me some input (exit to stop): ")
if user_input == 'exit':
print('Exiting')
done = True
else:
run_scheduled_task(user_input)
In my complex python program, when it's running, I have a piece of code that executes every 3 seconds that prints the program's progress as the percentage of the execution that's finished like so:
while len(dequeueingFinishedList)!=10:
print(str(len(masterListCSV_RowsListFinished)/float(len(masterListCSV_RowsList))*100) + "% done.")
time.sleep(3)
Is the time.sleep() function going to slow down my program? I read the that sleep function suspends execution. If it is slowing down my program, is there a more correct way of printing the progress to me every 3 seconds?
Yes, time.sleep will halt your program.
Use time.time in your loop and check when three seconds have passed.
time.sleep(seconds) will stop execution on the current thread. Therefore, it will completely stop your program on that thread: nothing else will happen until those seconds pass.
You don't have to worry about this. If the program uses threading, then the other threads shouldn't halt.
from time import time
prev = time()
while True:
now = time()
if now - prev > 3:
print 'report'
prev = now
else:
pass
# runs
The proper way to do this is with signal
import signal
def handler(signum, frame):
print i
if i>100000000:
raise Exception("the end")
else:
signal.alarm(3)
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
i=0
while True:
i+=1
import time
number = 1
while number > 0:
print "Testing"
time.sleep(5) #print every 5 seconds
That is just an example loop. I'm a semi-beginner and I'm not sure how to make a keypress(any key is fine) display how long the program has been running. This program will be running on Windows 7 and Linux.
Thank you very much.
Welcome to Stack Overflow and to Python! You'll like it here.
First, I'll show you how to print out the time your code has been running. The time module includes a time() function that gets the current time as a Unix timestamp (the number of seconds since January 1, 1970). If you assign it to a variable at the start of the function, you can simply call it each time through the loop and subtract it from the current time to get your runtime. With me so far?
(You can also remove your number variable and the number > 0 check and simply replace it with True.)
import time
start_time = time.time()
while True:
print "I've been running for %d seconds!" % (time.time() - start_time)
time.sleep(5) #print every 5 seconds
But you asked how to get it each time the user presses a key. If you just want 'enter', you can do:
import time
start_time = time.time()
while True:
print "I've been running for %d seconds!" % (time.time() - start_time)
raw_input("Press Enter...")
The raw_input() function will wait for the user to press Enter, then print out the runtime.
One problem at a time.
How do you find how long your program has been running at the point at which you want to calculate?
How do you detect a key-press?
How do you get the program to produce 1) when 2) happens?
Try each problem in turn, then ask if you need help.
There are a lot of complexities and approaches for a such a simple question.
If you are looking for up time of a currently running process, use the OS to query that process with the subprocess module to run a command line operation such as 'ps | grep "foo" '
Usually programs do only one thing at a time. For example, the code could either do work OR look for a keypress. If you need to run have to run two different sections of code concurrently, spawn (run) the code segments as separate threads . For your question you could spawn two threads (pieces of code), one to do work and one to query up time.
Use the threading module in python to wrap the worker function and create a query thread. However, when the worker thread is done, you will want the query thread to terminate also. One way to do this is to define it as a daemon thread. Daemon threads terminate when they are the only threads alive.
For example:
from time import sleep
import datetime
import threading
def do_someting():
MAX_RUN_TIME = 300 #Seconds
for i in xrange(MAX_RUN_TIME):
print i,
sleep (1)
class worker_thread(threading.Thread):
def run(self):
do_someting()
class keypress_daemon_thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self) # Initialize the parent class
self.daemon = True # Terminates if only daemon threads are left
def run(self):
startTime = datetime.datetime.now()
while True:
raw_input()
timeDelta = datetime.datetime.now() - startTime
print 'Up for', timeDelta
if __name__ == '__main__':
workerThread = worker_thread()
keyPressThread = keypress_daemon_thread()
workerThread.start()
keyPressThread.start()
workerThread.join()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to repeatedly execute a function every x seconds in Python?
Hi so here is the code I have:
client = myclient(info1,info2)
sellor()
Contractor()
It works perfectly but what I would like to do is to make python launch that code every 60 seconds indefinitely...
I don't actually understand how I have to put the code together with the time loop
Any help is appreciated
Thank's
If the 60 seconds ignores the time it takes to execute your code):
from time import sleep
while True:
sleep(60)
# your code here
but if the 60 seconds takes into account the time it takes to execute your code:
from time import sleep
from os import fork
while True:
sleep(60)
fork() # create child process
# your code here
Use the sleep method. Just create a loop (while, for, whatever) and sleep for 60 secs every iteration.
import time
while True:
client = myclient(info1,info2)
sellor()
Contractor()
time.sleep(10)
hope it works,all the best mate
import time
repeat_time = 3.0
while True:
start_time = time.time()
# Your code goes here
time.sleep(max(repeat_time - (time.time() - start_time), 0.0))
And your code will be executed exactly every "repeat_time"
You could use sleep as already mentioned. But because there may be a variable amount of time needed for your own functions to run, this wouldn't necessarily mean your functions are run every 60 seconds.
If it was important that the period between each start of your functions is closer to 60 seconds, you could use time. I haven't tried this but something like
import time
while True:
# Get the current time
startTime = time.time()
# Your functions
client = myclient(info1,info2)
sellor()
Contractor()
delay = True
while delay:
if time.time() - startTime > 60:
delay = False # Break the delay
You might also think of just scheduling the task through windows scheduler. The benefit here would end the script once run and then execute the script again after scheduled interval. In the second approach it seems that the script instance process would continually run and only use the sleep function to do nothing for the specified time. I take it this way if the scripts fails at any instance you might have to keep a check to restart the script. While as a scheduled activity the script will be executed in any case at that specified intervals.
You might also not want the process thread to be kept running for the python script executed. I will research on this and you might get to hear form our other folks in the mean while.
Regards,
Harshal