gpt4 book ai didi

python - 如何在 Python 中安排周期性任务?

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:22 24 4
gpt4 key购买 nike

如何在不阻塞的情况下在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com