是否有可能让这个.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)
答案 0 :(得分:1)
你有几种方法可以做到这一点。 如果你只想用Python做,你可以:
包装器解决方案的示例:
目标是创建一个新的python脚本,它将处理计时器,因此在需要时执行你的Twitter代码。
让我们说你当前的文件名为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)
这只是在函数中创建代码并添加一个记录行,在执行函数时打印当前时间。
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 = 10
和SLEEP_TIME = 5
(每10秒调用一次core.py,每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_TIME
或DELTA
,您将会错过一些来电所以不要每20分钟运行一次。
最后,因为您要在core.py
中导入wrapper.py
,您必须在与其他两个文件相同的文件夹中创建__init__.py
文件。 (/path/to/project/
应包含__init__.py
(空),core.py
和wrapper.py
)。
真正好的方法是创建一个守护进程,但它需要更多的技能。