我正在使用python和tweepy创建一个程序,该程序可以在Twitter上做两件事:
- 每隔 15 分钟发布一次推文
- 每 30 秒刮一次提及并回答其中的一些
我最终得到的是一个创建三个线程的程序:两个守护进程线程,每个任务一个,在后台运行,还有一个"主"线程,除了等待 TERM 信号取消其他两个并关闭程序之外,基本上什么都不做。 这是它的样子:
def run(self):
while self.running:
self.running= not self.handler.receivedTermSignal
time.sleep(1)
self.tweet.cancel()
self.mentions.cancel()
它似乎按预期工作,但感觉就像一个肮脏的黑客。难道没有更好的方法来处理这种事情吗?
你可以在Python 3中使用asyncio
。
import signal
import asyncio
from time import strftime
async def tweet():
while 1:
print(strftime('[%H:%M:%S]'), "tweet something")
try:
await asyncio.sleep(15 * 60)
except asyncio.CancelledError:
break
async def mentions():
while 1:
print(strftime('[%H:%M:%S]'), "scrape mentions and answer some of them")
try:
await asyncio.sleep(30)
except asyncio.CancelledError:
break
def shutdown():
print(strftime('[%H:%M:%S]'), "shutdown")
for task in asyncio.Task.all_tasks():
task.cancel()
def main():
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGTERM, shutdown)
tasks = [asyncio.ensure_future(tweet()), asyncio.ensure_future(mentions())]
loop.run_until_complete(asyncio.gather(*tasks))
if __name__ == "__main__":
main()