alwbtc
alwbtc

Reputation: 29445

How to stop a function at a specific time and continue with next function in python?

I have a code:

function_1()
function_2()

Normally, function_1() takes 10 hours to end. But I want function_1() to run for 2 hours, and after 2 hours, function_1 must return and program must continue with function_2(). It shouldn't wait for function_1() to be completed. Is there a way to do this in python?

Upvotes: 1

Views: 1893

Answers (5)

Hans Then
Hans Then

Reputation: 11322

You can time the execution using the datetime module. Probably your optimizer function has a loop somewhere. Inside the loop you can test how much time has passed since you started the function.

def function_1():
    t_end = datetime.time.now() + datetime.timedelta(hours=2)

    while not converged:
        # do your thing
        if datetime.time.now() > t_end:
            return

Upvotes: 0

tony
tony

Reputation: 1536

You can try to use module Gevent: start function in thread and kill that thread after some time.

Here is example:

import gevent

# function which you can't modify
def func1(some_arg)
    # do something
    pass

def func2()
    # do something
    pass

if __name__ == '__main__':
    g = gevent.Greenlet(func1, 'Some Argument in func1')
    g.start()
    gevent.sleep(60*60*2)
    g.kill()
    # call the rest of functions
    func2()

Upvotes: 1

jsbueno
jsbueno

Reputation: 110311

What makes functions in Python able to interrupt their execution and resuming is the use of the "yield" statement -- your function then will work as a generator object. You call the "next" method on this object to have it start or continue after the last yield

import time
def function_1():
    start_time = time.time()
    while True:
         # do long stuff
         running_time = time.time() -start_time
         if running_time > 2 * 60 * 60: # 2 hours
              yield #<partial results can be yield here, if you want>
              start_time = time.time()



runner = function_1()
while True:
    try:
        runner.next()
    except StopIteration: 
        # function_1 had got to the end
        break
    # do other stuff

Upvotes: 2

spicavigo
spicavigo

Reputation: 4224

from multiprocessing import Process
p1 = Process(target=function_1)
p1.start()
p1.join(60*60*2)
if p1.is_alive():p1.terminate()
function_2()

I hope this helps

I just tested this using the following code

import time
from multiprocessing import Process

def f1():
    print 0
    time.sleep(10000)
    print 1

def f2():
    print 2


p1 = Process(target=f1)
p1.start()
p1.join(6)
if p1.is_alive():p1.terminate()
f2()

Output is as expected:

0
2

Upvotes: 0

Eric
Eric

Reputation: 97601

If you don't mind leaving function_1 running:

from threading import Thread
import time

Thread(target=function_1).start()
time.sleep(60*60*2)
Thread(target=function_2).start()

Upvotes: 1

Related Questions