简体   繁体   English

在 Python 机器人中,如何每天只运行一次 function?

[英]In a Python bot, how to run a function only once a day?

I have a Python bot running PRAW for Reddit.我有一个为 Reddit 运行 PRAW 的 Python 机器人。 It is open source and thus users could schedule this bot to run at any frequency (eg using cron ).它是开源的,因此用户可以安排这个机器人以任何频率运行(例如使用cron )。 It could run every 10 minutes, or every 6 hours.它可以每 10 分钟或每 6 小时运行一次。

I have a specific function (let's call it check_logs ) in this bot that should not run every execution of this bot, but rather only once a day.我在这个机器人中有一个特定的 function (我们称之为check_logs ),它不应该运行这个机器人的每次执行,而是每天只运行一次。 The bot does not have a database.该机器人没有数据库。

Is there a way to accomplish this in Python without external databases/files?有没有办法在没有外部数据库/文件的情况下在 Python 中实现这一点?

Generally speaking, it's better (and easier) to use the external database or file.一般来说,使用外部数据库或文件会更好(也更容易)。 But, if you absolutely need it you could also:但是,如果您绝对需要它,您也可以:

  1. Modify the script itself, eg store the date of the last run in commented out last line of the script.修改脚本本身,例如将上次运行的日期存储在注释掉的脚本最后一行。
  2. Store the date of the last update on the web, for example, in your case it could be a Reddit post or google doc or draft email or a site like Pastebin, etc.将上次更新的日期存储在 web 上,例如,在您的情况下,它可能是 Reddit 帖子或谷歌文档或草稿 email 或 Pastebin 等网站。
  3. Change the "modified date" of the script itself and use it as a reference.更改脚本本身的“修改日期”并将其用作参考。

If you're using cron you can run it with command line arguments .如果您使用的是cron ,则可以使用命令行 arguments运行它。

And define in cron eg.并在 cron 中定义,例如。 python3 main.py daily for the daily run that you need and python3 main.py frequent for the other version. python3 main.py daily用于您需要的日常运行,而python3 main.py frequent用于其他版本。

I'm doing it that way and it worked optimally by now.我就是这样做的,现在效果最佳。

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

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