Python,使用线程和调度来保持 运行 函数不断
Python, Use threading and schedule to keep running a function constantly
我正在制作一个使用 instabot
自动发布到 Instagram 的机器人,现在的问题是,如果我超过请求数,机器人会在重试几分钟后终止脚本。
我想出的解决方案是每隔一小时左右将脚本安排到 运行,并确保脚本将持续保持 运行ning 我使用线程来重新启动发布功能当线程死了。
负责发布的函数,在此代码中,如果来自 instabot
的 bot 实例重试发送请求几分钟但失败,它将终止整个脚本。
def main():
create_db()
try:
os.mkdir("images")
print("[INFO] Images Directory Created")
except:
print("[INFO] Images Directory Found")
# GET A SUBMISSION FROM HOT
submissions = list(reddit.subreddit('memes').hot(limit=100))
for sub in submissions:
print("*"*68)
url = sub.url
print(f'[INFO] URL : {url}')
if "jpg" in url or "png" in url:
if not sub.stickied:
print("[INFO] Valid Post")
if check_if_exist(sub.id) is None:
id_ = sub.id
name = sub.title
link = sub.url
status = "FALSE"
print(f"""
[INFO] ID = {id_}
[INFO] NAME = {name}
[INFO] LINK = {link}
[INFO] STATUS = {status}
""")
# SAVE THE SUBMISSION TO THE DATABASE
insert_db(id_, name, link, status)
post_instagram(id_)
print(f"[INFO] Picture Uploaded, Next Upload is Scheduled in 60 min")
break
time.sleep(5 * 60)
调度函数:
def func_start():
schedule.every(1).hour.do(main)
while True:
schedule.run_pending()
time.sleep(10 * 60)
最后一段代码:
if __name__ == '__main__':
t = threading.Thread(target=func_start)
while True:
if not t.is_alive():
t.start()
else:
pass
所以基本上我想保持 运行 每隔一小时左右执行一次主要功能,但我没有取得任何成功。
在我看来 schedule
和 threading
对您的用例来说太过分了,因为您的脚本只执行一个任务,所以您不需要并发并且可以 运行 整个主线程中的东西。您主要只需要从 main
函数中捕获异常。我会选择这样的东西:
if __name__ == '__main__':
while True:
try:
main()
except Exception as e:
# will handle exceptions from `main` so they do not
# terminate the script
# note that it would be better to only catch the exact
# exception you know you want to ignore (rather than
# the very broad `Exception`), and let other ones
# terminate the script
print("Exception:", e)
finally:
# will sleep 10 minutes regardless whether the last
# `main` run succeeded or not, then continue running
# the infinite loop
time.sleep(10 * 60)
...除非你真的希望每个 main
运行 以 60 分钟的间隔 精确地 开始,在这种情况下你可能需要threading
或 schedule
。因为,如果 运行ning main
需要 3 到 5 分钟,那么在每次执行后简单地休眠 60 分钟意味着您将每 63 到 65 分钟启动一次函数。
我正在制作一个使用 instabot
自动发布到 Instagram 的机器人,现在的问题是,如果我超过请求数,机器人会在重试几分钟后终止脚本。
我想出的解决方案是每隔一小时左右将脚本安排到 运行,并确保脚本将持续保持 运行ning 我使用线程来重新启动发布功能当线程死了。
负责发布的函数,在此代码中,如果来自 instabot
的 bot 实例重试发送请求几分钟但失败,它将终止整个脚本。
def main():
create_db()
try:
os.mkdir("images")
print("[INFO] Images Directory Created")
except:
print("[INFO] Images Directory Found")
# GET A SUBMISSION FROM HOT
submissions = list(reddit.subreddit('memes').hot(limit=100))
for sub in submissions:
print("*"*68)
url = sub.url
print(f'[INFO] URL : {url}')
if "jpg" in url or "png" in url:
if not sub.stickied:
print("[INFO] Valid Post")
if check_if_exist(sub.id) is None:
id_ = sub.id
name = sub.title
link = sub.url
status = "FALSE"
print(f"""
[INFO] ID = {id_}
[INFO] NAME = {name}
[INFO] LINK = {link}
[INFO] STATUS = {status}
""")
# SAVE THE SUBMISSION TO THE DATABASE
insert_db(id_, name, link, status)
post_instagram(id_)
print(f"[INFO] Picture Uploaded, Next Upload is Scheduled in 60 min")
break
time.sleep(5 * 60)
调度函数:
def func_start():
schedule.every(1).hour.do(main)
while True:
schedule.run_pending()
time.sleep(10 * 60)
最后一段代码:
if __name__ == '__main__':
t = threading.Thread(target=func_start)
while True:
if not t.is_alive():
t.start()
else:
pass
所以基本上我想保持 运行 每隔一小时左右执行一次主要功能,但我没有取得任何成功。
在我看来 schedule
和 threading
对您的用例来说太过分了,因为您的脚本只执行一个任务,所以您不需要并发并且可以 运行 整个主线程中的东西。您主要只需要从 main
函数中捕获异常。我会选择这样的东西:
if __name__ == '__main__':
while True:
try:
main()
except Exception as e:
# will handle exceptions from `main` so they do not
# terminate the script
# note that it would be better to only catch the exact
# exception you know you want to ignore (rather than
# the very broad `Exception`), and let other ones
# terminate the script
print("Exception:", e)
finally:
# will sleep 10 minutes regardless whether the last
# `main` run succeeded or not, then continue running
# the infinite loop
time.sleep(10 * 60)
...除非你真的希望每个 main
运行 以 60 分钟的间隔 精确地 开始,在这种情况下你可能需要threading
或 schedule
。因为,如果 运行ning main
需要 3 到 5 分钟,那么在每次执行后简单地休眠 60 分钟意味着您将每 63 到 65 分钟启动一次函数。