我有一个python flask应用程序,当app.py运行时,我在内存中缓存一些数据。
有一个函数调用,如下所示:
cache_data()我想让这个函数每晚运行一次。有没有一种方法可以安排脚本自己重新运行,或者只在current_date的日期发生变化时调用函数?
if __name__ == "__main__":
port = 80
os.system("open http://localhost:{0}".format(port))
app.debug = True # Turn False later
app.run(host='0.0.0.0', port=port)发布于 2015-05-08 03:23:22
你可以在Python Rq中加入一个队列系统。
发布于 2015-05-08 03:26:25
您可以在app.py中产生一个调用/cache调用并休眠24小时的线程。
发布于 2015-05-08 03:38:18
你可以这样做:
if __name__ == "__main__":
when_to_run = # Set first run datetime
time_to_wait = when_to_run - datetime.now()
while True:
time.sleep(time_to_wait.seconds)
# run your stuff here
when_to_run = # Set next run datetime
time_to_wait = when_to_run - datetime.now()假设您希望每天上午10点运行此命令,您将when_to_run设置为今天上午10点运行,或者如果这已经是过去的时间,则设置为明天上午10点运行,并在循环中添加一天的时间增量。如果您只是设置为睡眠24小时,则执行时间将延迟到每次执行它所花费的时间。
示例:
每天下午1点运行东西:
if __name__ == "__main__":
when_to_run = datetime.now().replace(hour=13, minute=0, second=0, microsecond=0)
if datetime.now() > when_to_run:
# First run is tomorrow
when_to_run += timedelta(days=1)
time_to_wait = when_to_run - datetime.now()
while True:
time.sleep(time_to_wait.seconds)
# run your stuff here
stuff.run()
when_to_run += timedelta(days=1)
time_to_wait = when_to_run - datetime.now()https://stackoverflow.com/questions/30109726
复制相似问题