A decorator that notifies you via AWS-SNS if the function does not finish within the specified time

I wrote it for the first time using a decorator and a signal. A decorator that notifies you if the function does not finish within the specified time. It seems that you can use it to notify you of batches that are taking too long when you run nightly batches on AWS.

pytimekeeper.py


# -*- coding: utf-8 -*-                                                                                                                           
import signal
import boto.sns

def timeout(limit, topic, subject='Execution Timeout.', body='Please check program.', region='us-east-1'):
    '''                                                                                                                                           
How to use:A decorator that notifies you with aws sns if it does not finish within the specified execution time.
    @timeout(limit=3600, topic='arn:aws:sns:xxxxxxxx:yyyyyyy')                                                                                    
    def long_time_function():
        very_very_long_calc()                                                                                                               
    '''
    def notify_aws_sns(signum, frame):
        conn = boto.sns.connect_to_region(region)
        conn.publish(topic, body, subject)

    def __decorator(function):
        def __wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, notify_aws_sns)
            signal.alarm(limit)
            result = function(*args, **kwargs)
            signal.alarm(0)
            return result
        return __wrapper

    return __decorator

Recommended Posts

A decorator that notifies you via AWS-SNS if the function does not finish within the specified time
A decorator that does something if the function doesn't finish within the specified time
How to create a new file when the specified file does not exist — write if the file exists
Grep so that grep does not appear at the time of grep
If you are a beginner in programming, why not make a "game" for the time being? The story
When incrementing the value of a key that does not exist
If you give a list with the default argument of the function ...
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
A story that sometimes does not work if pip is up to date
I tried a neural network Π-Net that does not require an activation function
I tried to make a dictionary function that does not distinguish between cases
Examples and solutions that the Python version specified in pyenv does not run