Search code examples
pythonmultithreadingtimeout

Timeout child thread for python3


I am quite new to programming and I am running Linux, python3.5

There are a few similar questions in Stack Overflow but most of them do not have any response

like: [Python 2.7 multi-thread]In Python, how to timeout a function call in sub-thread?, and Python , Timeout on a function on child thread without using signal and thread.join

I am able to use signal when it is in main thread and timeout for multiprocess. However, the function I am currently running is a child thread using apscheduler (or it can be started directly)

schedule.add_job(test_upload.run, 'interval', seconds=10, start_date='2016-01-01 00:00:05',
                    args=['instant'])

and I can't convert it to child process because I am sharing database connection.

I have also tried https://stackoverflow.com/a/36904264/2823816, but terminal said

  result = await future.result(timeout = timeout)
                        ^
SyntaxError: invalid syntax

in

import concurrent

def run():
    return 1

timeout = 10

with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(run) # get a future object
    try:
        result = await future.result(timeout = timeout)
    except concurrent.futures.TimeOutError:
        result = None

I am now very sure how to solve it:( Thanks for any help.


Solution

  • I gave up timing out the thread in my child thread.

    So I used multi-process within the child thread to kill it. I could not find any other solution.