简体   繁体   中英

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

I have a Python bot running PRAW for Reddit. It is open source and thus users could schedule this bot to run at any frequency (eg using cron ). It could run every 10 minutes, or every 6 hours.

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. The bot does not have a database.

Is there a way to accomplish this in Python without external databases/files?

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.
  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 .

And define in cron eg. python3 main.py daily for the daily run that you need and python3 main.py frequent for the other version.

I'm doing it that way and it worked optimally by now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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