简体   繁体   English

每 2 秒运行一次 python

[英]Run python every 2 seconds

I know how to start a function every x seconds or minute.我知道如何每隔 x 秒或每分钟启动一个 function。 The main problem is that it happens that my script stops for « no reason » or that windows crashs.主要问题是我的脚本“无缘无故”停止或 windows 崩溃。 Ram was ok at that time.拉姆当时还好。 I can't let this happens.我不能让这种事情发生。 So instead of running the script forever and call a function every 2 or 3 seconds to check my gmail emails or make it sleep every 2 seconds, I am looking for one of these alternatives:因此,与其永远运行脚本并每 2 或 3 秒调用一次 function 来检查我的 gmail 电子邮件或使其每 2 秒休眠一次,我正在寻找以下替代方案之一:

  • Windows: at email reception (gmail), run my script and read its header Windows:在 email 接收 (gmail),运行我的脚本并阅读它的 header
  • Windows: open and run the script every 3 seconds to check for new emails then close it. Windows:每 3 秒打开并运行一次脚本以检查新电子邮件,然后将其关闭。
  • Other alternatives (web service or other)其他替代方案(网络服务或其他)

Zapier was a good alternative. Zapier 是一个不错的选择。 At email reception (api) run python.在 email 接收 (api) 处运行 python。 But it's not possible to import library so that doesn't fit my needs.但是无法导入库,因此不符合我的需求。

I'm working on MacOS so I know I have the possibility to run it with crontab but this not an option since I don't want to make it run forever on my desk.我正在使用 MacOS,所以我知道我可以使用 crontab 运行它,但这不是一个选项,因为我不想让它永远在我的办公桌上运行。

You could use the shedule library: https://schedule.readthedocs.io/en/stable/ .您可以使用 shedule 库: https://schedule.readthedocs.io/en/stable/ Here it's an example:这是一个例子:

import schedule

schedule.every(interval).seconds.do(function)
while True:
     schedule.run_pending()

You need to install the library: pip install schedule您需要安装库: pip install schedule

Maybe try to deploy on Pythonanywhere, you can schedule a task/run a script every x.也许尝试在 Pythonanywhere 上部署,您可以每 x 安排一个任务/运行一个脚本。 https://help.pythonanywhere.com/pages/ScheduledTasks/ https://help.pythonanywhere.com/pages/ScheduledTasks/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM