python - 从 Crontab 开始的简单 Huey 示例的挑战
问题描述
我正在尝试将 Huey 文档中建议的代码组织实施到现有应用程序中,并遵循简单的示例。目标是构建一个每天凌晨 3:00 运行任务的 crontab。
我打开了两个终端选项卡,第一个是消费者运行示例中的脚本:
PYTHONPATH=.:$PYTHONPATH
export WORKER_CLASS=${1:-thread}
huey_consumer.py main.huey --workers=4 -k $WORKER_CLASS -C -S
然后,在另一个选项卡中,我运行 main.py 脚本:
python main.py
配置文件
from huey import SqliteHuey
huey = SqliteHuey(filename='/tmp/huey.db')
任务.py
from config import huey
# Note that this time is 1 minute before whenever I'm debugging.
# I'm using the 3 am example as what we're aiming for in our final product.
@huey.periodic_task(crontab(minute='0', hour='3'))
def run_this_function():
system = New_Class() # Class instantiation since there's a bunch that happens when a new class is set up
system.run_method # Runs a bunch of methods from the class in one location
主文件
from config import huey
from tasks import run_this_function
def main:
run_this_function()
if __name__ == "__main__":
main()
该任务立即运行,并且由于我对 Huey 是全新的,不确定我可能会缺少什么以使其按计划工作。我尝试了很多 crontab 组合,不确定是否存在挑战,或者我如何run_this_function
在main
方法中调用。任何帮助表示赞赏!
解决方案
因此,首先,您实际上并不想调用run_this_function()
自己,因此无需main.py
在另一个选项卡中运行您的脚本。您只需要让 huey 消费者运行,因为您希望它负责在请求的时间执行任务。
您的消费者需要能够发现任务,您可以通过将其导入到该主文件中来执行此操作,然后通过该文件启动 Huey 实例(您也在执行此操作)。一个简单的测试可能是将打印语句放在与您定义周期性任务的文件相同的文件中。运行消费者后,您应该会看到您的打印语句。如果没有,您的任务也不会被消费者接走。
其次,我建议不要使用该crontab
功能。我过去无法让它工作,相反,您最好编写自己的函数来配置凌晨 3 点。Huey 使用当前时间戳定期调用提供的函数。因此,作为一个可重用的示例,您可以执行以下操作:
def run_at_my_preferred_hour(hour_to_run):
last_day_it_ran_for = None
def check_if_task_needs_to_run_for_this_time(current_timestamp):
if current_timestamp.hour == hour_to_run and current_timestamp.day != last_day_it_ran_for:
# Save that you already ran the task for this day
last_day_it_ran_for = current_timestamp.day
return True
return False
return check_if_task_needs_to_run_for_this_time
@huey.periodic_task(run_at_my_preferred_hour(3))
def run_this_function():
...
推荐阅读
- python - 熊猫删除具有多个字符串条件的行
- elasticsearch - elasticsearch搜索像sql中的“distint count”?
- rust - 库箱中多个可执行文件的文件布局
- python - 如何将函数应用于数据框中的所有列并在python中以数据框的形式输出
- ios - 如何在 Objective-C 或 Swift 上发送带有 .p12 证书的 https 请求
- c# - 如何显示字符串的第二个值的格式字符串?
- stock - 以编程方式检查今天是否是市场开放交易日
- ruby-on-rails - 我们可以在rails应用程序中加密一个压缩的java脚本文件吗?
- javascript - HTML 中的 JSON 解析
- python - 如何在 python-django 中使用 woocommerce api 获取所有没有隐藏(私有)产品的产品?