All Projects → kata198 → Func_timeout

kata198 / Func_timeout

Licence: lgpl-3.0
Python module which allows you to specify timeouts when calling any existing function, and support for stoppable threads

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Func timeout

Rpmalloc
Public domain cross platform lock free thread caching 16-byte aligned memory allocator implemented in C
Stars: ✭ 1,218 (+734.25%)
Mutual labels:  thread
Playwright Aws Lambda
Support for running Microsoft's Playwright on AWS Lambda and Google Cloud Functions
Stars: ✭ 107 (-26.71%)
Mutual labels:  function
M5p01 muprokaron
A tiny real-time kernel focusing on formal reliability and simplicity.
Stars: ✭ 132 (-9.59%)
Mutual labels:  thread
Service
Service encapsulates an object which executes a bit of code in a loop that can be started or stopped and query whether it is running or not.
Stars: ✭ 86 (-41.1%)
Mutual labels:  thread
Func Loc
A simple tool that helps you to retrieve the function location from its reference.
Stars: ✭ 99 (-32.19%)
Mutual labels:  function
React Native Workers
Do heavy data process outside of your UI JS thread.
Stars: ✭ 114 (-21.92%)
Mutual labels:  thread
Diskqueue
A thread-safe, multi-process(ish) persistent queue library for .Net and Mono
Stars: ✭ 66 (-54.79%)
Mutual labels:  thread
Gl vk threaded cadscene
OpenGL and Vulkan comparison on rendering a CAD scene using various techniques
Stars: ✭ 143 (-2.05%)
Mutual labels:  thread
Spek
🎏 Function builder BDD testing framework in Swift
Stars: ✭ 104 (-28.77%)
Mutual labels:  function
Async Sockets Cpp
Simple thread-based asynchronous TCP & UDP Socket classes in C++.
Stars: ✭ 127 (-13.01%)
Mutual labels:  thread
Livestream Kt
LiveStream is a simple class which makes communication easy among different modules of your application.
Stars: ✭ 92 (-36.99%)
Mutual labels:  thread
Shellfuncs
Python API to execute shell functions as they would be Python functions
Stars: ✭ 96 (-34.25%)
Mutual labels:  function
React Papaparse
react-papaparse is the fastest in-browser CSV (or delimited text) parser for React. It is full of useful features such as CSVReader, CSVDownloader, readString, jsonToCSV, readRemoteFile, ... etc.
Stars: ✭ 116 (-20.55%)
Mutual labels:  thread
Easyble
Multi-devices process Bluetooth library for Android
Stars: ✭ 81 (-44.52%)
Mutual labels:  thread
Unitask
Provides an efficient allocation free async/await integration for Unity.
Stars: ✭ 2,547 (+1644.52%)
Mutual labels:  thread
Laravel 5 Messenger
A Simple Laravel 5, 6, 7 & 8 Messenger with Pusher Capabilities
Stars: ✭ 75 (-48.63%)
Mutual labels:  thread
Hfunc
java implement Higher-order function ,support map,filter , reduce with parallel, android
Stars: ✭ 112 (-23.29%)
Mutual labels:  function
Detour Rs
A cross-platform detour library written in Rust
Stars: ✭ 146 (+0%)
Mutual labels:  function
Avoid Memory Leak Android
🔥 Examples of memory leaks and common patterns that cause them in Android development and how to fix/avoid them
Stars: ✭ 140 (-4.11%)
Mutual labels:  thread
Utils.js
Useful JavaScript Functions Collection 一些很实用的JavaScript函数封装集合
Stars: ✭ 121 (-17.12%)
Mutual labels:  function

func_timeout

Python module to support running any existing function with a given timeout.

Function Timeout

func_timeout

This is the function wherein you pass the timeout, the function you want to call, and any arguments, and it runs it for up to #timeout# seconds, and will return/raise anything the passed function would otherwise return or raise.

def func_timeout(timeout, func, args=(), kwargs=None):
	'''
		func_timeout - Runs the given function for up to #timeout# seconds.

		Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut

		@param timeout <float> - Maximum number of seconds to run #func# before terminating
		@param func <function> - The function to call
		@param args    <tuple> - Any ordered arguments to pass to the function
		@param kwargs  <dict/None> - Keyword arguments to pass to the function.

		@raises - FunctionTimedOut if #timeout# is exceeded, otherwise anything #func# could raise will be raised

		@return - The return value that #func# gives
	'''

Example

So, for esxample, if you have a function "doit('arg1', 'arg2')" that you want to limit to running for 5 seconds, with func_timeout you can call it like this:

from func_timeout import func_timeout, FunctionTimedOut

...

try:

	doitReturnValue = func_timeout(5, doit, args=('arg1', 'arg2'))

except FunctionTimedOut:
	print ( "doit('arg1', 'arg2') could not complete within 5 seconds and was terminated.\n")
except Exception as e:
	# Handle any exceptions that doit might raise here

func_set_timeout

This is a decorator you can use on functions to apply func_timeout.

Takes two arguments, "timeout" and "allowOverride"

If "allowOverride" is present, an optional keyword argument is added to the wrapped function, 'forceTimeout'. When provided, this will override the timeout used on this function.

The "timeout" parameter can be either a number (for a fixed timeout), or a function/lambda. If a function/lambda is used, it will be passed the same arguments as the called function was passed. It should return a number which will be used as the timeout for that paticular run. For example, if you have a method that calculates data, you'll want a higher timeout for 1 million records than 50 records.

Example:

@func_set_timeout(2.5)
def myFunction(self, arg1, arg2):
	...

FunctionTimedOut

Exception raised if the function times out.

Has a "retry" method which takes the following arguments:

* No argument - Retry same args, same function, same timeout
* Number argument - Retry same args, same function, provided timeout
* None - Retry same args, same function, no timeout

How it works

func_timeout will run the specified function in a thread with the specified arguments until it returns, raises an exception, or the timeout is exceeded. If there is a return or an exception raised, it will be returned/raised as normal.

If the timeout has exceeded, the "FunctionTimedOut" exception will be raised in the context of the function being called, as well as from the context of "func_timeout". You should have your function catch the "FunctionTimedOut" exception and exit cleanly if possible. Every 2 seconds until your function is terminated, it will continue to raise FunctionTimedOut. The terminating of the timed-out function happens in the context of the thread and will not block main execution.

StoppableThread

StoppableThread is a subclass of threading.Thread, which supports stopping the thread (supports both python2 and python3). It will work to stop even in C code.

The way it works is that you pass it an exception, and it raises it via the cpython api (So the next time a "python" function is called from C api, or the next line is processed in python code, the exception is raised).

Using StoppableThread

You can use StoppableThread one of two ways:

As a Parent Class

Your thread can extend func_timeout.StoppableThread.StoppableThread and implement the "run" method, same as a normal thread.

from func_timeout.StoppableThread import StoppableThread

class MyThread(StoppableThread):

	def run(self):
		
		# Code here
		return

Then, you can create and start this thread like:

myThread = MyThread()

# Uncomment next line to start thread in "daemon mode" -- i.e. will terminate/join automatically upon main thread exit

#myThread.daemon = True

myThread.start()

Then, at any time during the thread's execution, you can call .stop( StopExceptionType ) to stop it ( more in "Stopping a Thread" below

Direct Thread To Execute A Function

Alternatively, you can instantiate StoppableThread directly and pass the "target", "args", and "kwargs" arguments to the constructor

myThread = StoppableThread( target=myFunction, args=('ordered', 'args', 'here'), kwargs={ 'keyword args' : 'here' } )

# Uncomment next line to start thread in "daemon mode" -- i.e. will terminate/join automatically upon main thread exit

#myThread.daemon = True

myThread.start()

This will allow you to call functions in stoppable threads, for example handlers in an event loop, which can be stopped later via the .stop() method.

Stopping a Thread

The StoppableThread class (you must extend this for your thread) adds a function, stop, which can be called to stop the thread.

def stop(self, exception, raiseEvery=2.0):
	'''
		Stops the thread by raising a given exception.

		@param exception <Exception type> - Exception to throw. Likely, you want to use something

		  that inherits from BaseException (so except Exception as e: continue; isn't a problem)

		  This should be a class/type, NOT an instance, i.e.  MyExceptionType   not  MyExceptionType()


		@param raiseEvery <float> Default 2.0 - We will keep raising this exception every #raiseEvery seconds,

			until the thread terminates.

			If your code traps a specific exception type, this will allow you #raiseEvery seconds to cleanup before exit.

			If you're calling third-party code you can't control, which catches BaseException, set this to a low number
			 
			  to break out of their exception handler.


		 @return <None>
	'''

The "exception" param must be a type, and it must be instantiable with no arguments (i.e. MyExceptionType() must create the object).

Consider using a custom exception type which extends BaseException, which you can then use to do basic cleanup ( flush any open files, etc. ).

The exception type you pass will be raised every #raiseEvery seconds in the context of that stoppable thread. You can tweak this value to give yourself more time for cleanups, or you can shrink it down to break out of empty exception handlers ( try/except with bare except ).

Notes on Exception Type

It is recommended that you create an exception that extends BaseException instead of Exception, otherwise code like this will never stop:

while True:
	try:
		doSomething()
	except Exception as e:
		continue

If you can't avoid such code (third-party lib?) you can set the "repeatEvery" to a very very low number (like .00001 ), so hopefully it will raise, go to the except clause, and then raise again before "continue" is hit.

You may want to consider using singleton types with fixed error messages, so that tracebacks, etc. log that the call timed out.

For example:

class ServerShutdownExceptionType(BaseException):

	def __init__(self, *args, **kwargs):

		BaseException.__init__(self, 'Server is shutting down')

This will force 'Server is shutting down' as the message held by this exception.

Pydoc

Find the latest pydoc at http://htmlpreview.github.io/?https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html?vers=4.3.5 .

Support

I've tested func_timeout with python 2.7, 3.4, 3.5, 3.6, 3.7. It should work on other versions as well.

Works on windows, linux/unix, cygwin, mac

ChangeLog can be found at https://raw.githubusercontent.com/kata198/func_timeout/master/ChangeLog

Pydoc can be found at: http://htmlpreview.github.io/?https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html?vers=1

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].