Python 如何仅运行5分钟的函数?

Python 如何仅运行5分钟的函数?,python,django,scheduling,Python,Django,Scheduling,我的logger_功能需要运行5分钟。有没有带计时器的计时器装饰程序或线程销毁程序?我怎样才能做到这一点。 我的for循环正在切换键并发送到logger函数,如果try有任何问题,除了阻止其正常运行,但是如果SyncCommand一切正常,可能需要很多小时,但我只想在前5分钟内记录错误。有计时器装饰器吗 import logging from a.x.models import X from a.x.management.commands.syncx \ import Command

我的logger_功能需要运行5分钟。有没有带计时器的计时器装饰程序或线程销毁程序?我怎样才能做到这一点。 我的for循环正在切换键并发送到logger函数,如果try有任何问题,除了阻止其正常运行,但是如果SyncCommand一切正常,可能需要很多小时,但我只想在前5分钟内记录错误。

有计时器装饰器吗

import logging

from a.x.models import X
from a.x.management.commands.syncx \
    import Command as SyncCommand

from a.x.adapter_classes import ADAPTER_CLASSES

LOGGER = logging.getLogger(__name__)


def logger_function(code):
    if not X.objects.filter(code=code).exists():
        X.objects.create(code=code)
        LOGGER.info(f"{X} created")

    args = []
    kwargs = {'x_code': code,
              'class': False,
              'database': 'default'}

    try:
        LOGGER.info(f"Starting syncx command for {code}")
        #or this command needs to be run just 5 minutes for every key
        SyncCommand().handle(*args, **kwargs)
        LOGGER.info(f"There is no error for {code}")

    except Exception as error:
        with open("logger.txt", "a") as file:
            file.write(f"{code}'s error is : {error}")
            LOGGER.info(f"Logging error about {code}\n")


def run():
    for key in ADAPTER_CLASSES.keys():
        #this function needs to be run just 5 minutes for every key
        logger_function(key)

如果允许您使用外部库,我建议您看看。

我通过使用信号库解决了这个问题

    # importing the required module 
import timeit 
  
# code snippet to be executed only once 
mysetup = "from math import sqrt"
  
# code snippet whose execution time is to be measured 
mycode = ''' 
def example(): 
    mylist = [] 
    for x in range(100): 
        mylist.append(sqrt(x)) 
'''
  
# timeit statement 
print timeit.timeit(setup = mysetup, 
                    stmt = mycode, 
                    number = 10000) 

5分钟结束后会发生什么?如果记录器正在做重要的事情,当发生这种情况时,当5分钟结束命令应该停止,命令必须为下一个键启动。我的目的是记录错误,如果在5分钟内正确工作,我确信密钥也不会出错。
def handler(signum, frame):
    raise Exception(None)

#do stuff func

 for key in ADAPTER_CLASSES.keys():
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(300) #5 min
        logger_function(key)
        signal.alarm(0)