如何安排功能作为后台任务运行
How to schedule a function to operate as a background task
为我糟糕的措辞道歉,但这里是。
我需要每三十分钟执行一次功能,而其他任务是 运行,但我不知道如何执行此操作或将其表达为 google。我的目标是修改我的脚本,使其像具有后台服务、程序、实用程序等的任务管理器程序一样运行(没有 UI)。
我试图通过为每个函数计时和创建执行其他函数的函数来创建它,但是无论我尝试什么,它都像任何脚本一样以异步方式运行。
这方面的一个例子包括以下内容。
def function_1():
"""Perform operations"""
pass
def function_2():
"""Perform operations"""
pass
def executeAllFunctions():
function_1()
function_2()
如何在 function_2
以正常方式执行的同时将 function_1
初始化为后台任务?
有一个很好的答案。
主要思想是 运行 线程内永远循环中的异步协程。
在您的情况下,您必须将函数一定义为协同程序,使用调用函数进入线程并创建线程。
示例在很大程度上启发了 link 中的答案,但适应了您的问题。
@asyncio.coroutine
def function_1():
while True:
do_stuff
yield from asyncio.sleep(1800)
def wrapper(loop):
asyncio.set_event_loop(loop)
loop.run_until_complete(function_1())
def function_2():
do_stuff
def launch():
loop = asyncio.get_event_loop()
t = threading.Thread(target=wrapper, args=(loop,)) # create the thread
t.start() # launch the thread
function_2()
t.exit() # when function_2 return
为我糟糕的措辞道歉,但这里是。
我需要每三十分钟执行一次功能,而其他任务是 运行,但我不知道如何执行此操作或将其表达为 google。我的目标是修改我的脚本,使其像具有后台服务、程序、实用程序等的任务管理器程序一样运行(没有 UI)。
我试图通过为每个函数计时和创建执行其他函数的函数来创建它,但是无论我尝试什么,它都像任何脚本一样以异步方式运行。
这方面的一个例子包括以下内容。
def function_1():
"""Perform operations"""
pass
def function_2():
"""Perform operations"""
pass
def executeAllFunctions():
function_1()
function_2()
如何在 function_2
以正常方式执行的同时将 function_1
初始化为后台任务?
有一个很好的答案
在您的情况下,您必须将函数一定义为协同程序,使用调用函数进入线程并创建线程。
示例在很大程度上启发了 link 中的答案,但适应了您的问题。
@asyncio.coroutine
def function_1():
while True:
do_stuff
yield from asyncio.sleep(1800)
def wrapper(loop):
asyncio.set_event_loop(loop)
loop.run_until_complete(function_1())
def function_2():
do_stuff
def launch():
loop = asyncio.get_event_loop()
t = threading.Thread(target=wrapper, args=(loop,)) # create the thread
t.start() # launch the thread
function_2()
t.exit() # when function_2 return