如何在 python 中安排周期性任务而不阻塞?
这是一个简单的情况。假设此票证变量在 2 小时后失效。所以我需要从服务中获取它。
ticket = 1 # It expires every 2 hours
def process_using_ticket(): # This function is called using a get request from flask server
print('hello', ticket)
如何在不阻塞的情况下每两小时重置为 1?
一种方法可能是启动一个线程并休眠 2 小时,然后重置变量,但我想知道是否有更好的替代方案。
注意:一切都在 Docker 中运行。
最佳答案
这看起来像是 cron
的用例,一个在所有 Linux 机器上都能找到的简单实用程序,用于安排定期任务。可以创建一个简单的 cron 任务,如下所示:
$ crontab -e
在 cron 中,输入一个条目
0 */2 * * * /home/username/ticket_script.py
确保您的脚本具有可执行权限。如果您要在脚本中打印某些内容,请使用 cron 条目来重定向其输出,例如
0 */2 * * * /home/username/ticket_script.py >> /home/username/ticket_script_runs.log
对于在 Docker 中运行此程序的问题,您可以通过此线程 -> https://forums.docker.com/t/cronjobs-in-docker-container/2618/5其中说:
Most Docker containers only run the binary you specify (in this case /bin/bash), so there is no cron daemon running to trigger these jobs.
There are a number of ways you can deal with this - for small adhoc things, you can add the cron entry to your host's crontab, and trigger the job in the container using docker exec containername ...
You can replace the container entrypoint with a shell script that starts the cron, or if you have a need for several services, use something like supervisord to manage them.
And if you're going all in, you can make a cron container which you can then use to kick off tasks using docker exec.
另一种方法是您已经拥有的方法 - 睡 2 小时,或者维护 time_last_read
时间戳,不断评估自上次读取以来是否已过去 2 小时 (time_now - time_last_read >= 2_HOURS
),一旦条件为 True,则将值重新读入内存并重置 time_last_read
。
关于python - 如何在Python中安排周期性任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47673008/