On 13/02/2015, at 10:14 PM, Paul Royik <[email protected]> wrote:

> I'm sure, that this algorithm is a root of problem.
> Other pages are not a problem.
> 
> How can I limit a time wthout a thread or stop it?
> 
> For now code is following:
> 
> @time_limit(45)
> def decorator(my_params):
>   return integrate(my_params)
> 
> def my_views(request):
>     try:
>        result = decorator(my_params)
>    except TimeOutException: #actually any exception
>        # how to stop a thread????
>        result = ''
>    return HttpResponse(.....)
> 
> How to stop a thread?

It isn't about stopping a separate thread.

Your algorithm has to periodically check a flag and raise an exception to get 
out of the algorithm.

import functools
import time
import threading

def time_limit(seconds):
    def decorator(func):
        func.info = threading.local()

        def die_on_timeout():
            if time.time() > func.info.end_time:
                raise RuntimeError('timeout')

        func.die_on_timeout = die_on_timeout

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            func.info.end_time = time.time() + seconds
            return func(*args, **kwargs)

        return wrapper

    return decorator

@time_limit(20)
def algorithm():
    while True:
        algorithm.die_on_timeout()
        print 'sleep'
        time.sleep(1)

algorithm()

I only use threading.local() here so it is safe in a multithreaded environment.

I am not creating separate threads.

Graham

-- 
You received this message because you are subscribed to the Google Groups 
"modwsgi" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/modwsgi.
For more options, visit https://groups.google.com/d/optout.

Reply via email to