是否可以使此.py脚本每 20 分钟超时一次并自行自动运行?



是否可以使此.py脚本每 20 分钟超时一次并自行自动运行?

目前,我正在使用 crontab 每 20 分钟重新运行一次它,但问题是它有时会运行多个.py,而不是实际重新运行该程序。我只希望它每 20 分钟重新运行一次,而不是每 20 分钟重新运行一次它的另一个实例。

#!/usr/bin/env python
from TwitterFollowBot import TwitterBot
my_bot = TwitterBot("/home/TwitterFollowBot/config.txt")
my_bot.sync_follows()
my_bot.auto_unfollow_nonfollowers()
my_bot.auto_rt("@RtwtKing", count=2000)
my_bot.auto_rt("@ShoutGamers", count=2000)

您有几种方法可以执行此操作。 如果你只想用Python来做,你可以:

使用线程,
  • 它会很好地工作,但这并不是线程的真正目的。
  • 使用守护程序(这里很好的例子)
  • 做一个 Python 包装器,它将永远循环,并在需要时调用你的脚本。它不那么干净,但也不那么矫枉过正。

包装器解决方案示例:

目标是创建一个新的python脚本来处理计时器,从而在需要时执行你的Twitter代码。

1. 更新当前代码以将其封装在方法中

假设您当前的文件名为core.py

core.py

from datetime import datetime
from TwitterFollowBot import TwitterBot
def get_feed():
print "({}) LOG: get_feed starting".format(datetime.now())
my_bot = TwitterBot("/home/TwitterFollowBot/config.txt")
my_bot.sync_follows()
my_bot.auto_unfollow_nonfollowers()
my_bot.auto_rt("@RtwtKing", count=2000)
my_bot.auto_rt("@ShoutGamers", count=2000)

这只是在函数中制作代码并添加一个日志记录行,该日志记录行在执行函数时打印当前时间。

2.制作一个包装器来处理计时器并调用您的推特代码

wrapper.py

import time
from datetime import datetime
# Import your twitter code, so you can use it by calling 'get_feed()'
from core import get_feed
# Define constants here because it's easier to find it on top of file
# Delta between the last call and the next one, bascially time between two calls: 20 minutes
DELTA = 20 * 60
# Time your wrapper will take between each verification: 5 minutes
SLEEP_TIME = 5 * 60
# Initialize timer and call for the first time your method
# last_run will store timestamp of the last time you called get_feed()
last_run = time.time()
get_feed()
# Start an inifinite loop
while True:
# Compute delta since last call
# last_run_delta will store the time in seconds between last call and now
last_run_delta = time.time() - last_run
# If last_run_delta is upper than DELTA so the number of seconds you want to separate two calls is reached.
if last_run_delta >= DELTA:
# Because time is reached you want to run again your code and reset timer to can handle next call
last_run = time.time()
get_feed()
# If you have not reach delta time yet, you want to sleep to avoid stack overflow and because you don't need to check each microseconds
else:
time.sleep(SLEEP_TIME)

带有DELTA = 10SLEEP_TIME = 5的输出(core.py 每 10 秒调用一次,每 5 秒进行一次检查):

(2016-11-29 10:43:07.405750) LOG: get_feed starting
(2016-11-29 10:43:17.414629) LOG: get_feed starting
(2016-11-29 10:43:27.422033) LOG: get_feed starting
(2016-11-29 10:43:37.430698) LOG: get_feed starting
(2016-11-29 10:43:47.436595) LOG: get_feed starting

这种方法唯一真正的好处是你不能一次启动相同的进程两次。因为它不是异步的,所以get_feed不能调用两次,但如果get_feed花费的时间超过SLEEP_TIMEDELTA,您将错过一些呼叫,因此不要每 20 分钟运行一次。

最后一件事,因为您要在wrapper.py中导入core.py,所以您必须在与其他两个文件相同的文件夹中创建一个__init__.py文件。(/path/to/project/应包含__init__.py(空)、core.pywrapper.py)。

真正好的方法就是创建一个守护进程,但它需要更多的技能。

最新更新