[英]How can I run a function for just 5 minutes?
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)
我的 logger_function 需要運行 5 分鍾。 有沒有帶定時器的定時器裝飾器或線程銷毀器? 我怎樣才能做到這一點。 我的 for 循環正在轉移鍵並發送到記錄器 function,如果除了阻止它的 okey 之外嘗試有任何問題,但如果一切都適合我的 SyncCommand,它可能需要幾個小時,但我只想在前 5 分鍾內記錄錯誤。
有沒有定時器裝飾器
如果您被允許使用外部庫,我建議您查看timeout-decorator 。
# 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)
我使用信號庫解決了它
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.