我正在尝试执行我不关心何时以及如何完成的任务。它是Python3.5,并且没有安装或想要的其他异步软件包,只是“asyncio”。
有一个很好的包“计划”可以很好地安排:
import schedule
schedule.every(5).seconds.do(call_my_remote_url)
while 1:
schedule.run_pending()
time.sleep(1)
有一个火灾和遗忘代码可以完成它的工作:
def fire_and_forget(task, *args, **kwargs):
loop = asyncio.get_event_loop()
if callable(task):
return loop.run_in_executor(None, task, *args, **kwargs)
else:
raise TypeError('Task must be a callable')
然而,当我把它放在一起时:
import schedule
import time
import datetime
import asyncio
def call_my_remote_url():
# Do stuff, completion of which I don't care. For example
print("started @ "+str(datetime.datetime.now().time()))
time.sleep(5)
print("completed @ " + str(datetime.datetime.now().time()))
def fire_and_forget(task, *args, **kwargs):
loop = asyncio.get_event_loop()
if callable(task):
return loop.run_in_executor(None, task, *args, **kwargs)
else:
raise TypeError('Task must be a callable')
schedule.every(5).seconds.do(fire_and_forget(call_my_remote_url))
while 1:
schedule.run_pending()
time.sleep(1)
它悲惨地失败了:
(env) $ python3 example_fire_and_forget_with_scheduler.py
started @ 12:19:04.901547
Traceback (most recent call last):
File "example_fire_and_forget_with_scheduler.py", line 21, in <module>
schedule.every(5).seconds.do(fire_and_forget(call_my_remote_url))
File "/Users/user/Projects/env/lib/python3.5/site-packages/schedule/__init__.py", line 352, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
completed @ 12:19:09.906020
(env)$
似乎“shedule”模块不开心,btu我不明白为什么以及如何解决它。任何想法或简单替代品?
(请注意,它不仅仅是异步,而且必须按计划忘记火灾)
答案 0 :(得分:1)
你以不喜欢的方式将参数传递给do
。稍微简化问题,以下似乎有效:
import schedule
import time
import datetime
def call_my_remote_url():
# Do stuff, completion of which I don't care. For example
print("started @ "+str(datetime.datetime.now().time()))
time.sleep(5)
print("completed @ " + str(datetime.datetime.now().time()))
def fire_and_forget(task, *args, **kwargs):
if callable(task):
return task()
else:
raise TypeError('Task must be a callable')
schedule.every(5).seconds.do(fire_and_forget, call_my_remote_url)
while 1:
schedule.run_pending()
time.sleep(1)
因此fire_and_forget
的参数会传递给do
。我似乎无法在文档中找到详细信息,但this example暗示了这一点。