簡體   English   中英

如何使用附加配置自動化調度

[英]How to automatize scheduling with additional configuration

考慮到我需要經常向我的客戶發送自動報告電子郵件。 由於我可能有不止一位客戶,並且一位客戶可能需要每日和/或每周報告,我想將這些作為report_config.json保存在 json 文件中,並使用 python schedule模塊將其自動化。

到目前為止我已經嘗試過:

report_config.json看起來像這樣:

{
    "cusomer1": [
        {
            "report_type": "twitter",
            "report_frequency": "daily",
            "receivers": [
                "example@example.com"
            ]
        },
        {
            "report_type": "twitter",
            "report_frequency": "weekly",
            "receivers": [
                "example@example.com"
            ]
        }
    ],
    "customer2": {
        "report_type": "twitter",
        "report_frequency": "daily",
        "receivers": [
                "example@example.com"
            ]
    }
}

就像我想將客戶的 email 需求保留在列表中,作為配置文件中的值。 然后循環並安排它們。 IE:

if __name__ == "__main__":
    for customer, reports in report_config.items():
        for report in reports:
            # below is an example of scheduling and not working as I want to achieve right now
            schedule.every().days.at('03:00').do(preprare_report,
                                                 report['report_type'], report['report_frequency'])
            schedule.every().monday.at('03:00').do(preprare_report,
                                                   report['report_type'], report['report_frequency'])

    while True:
        schedule.run_pending()
        time.sleep(1)

但正如您所見,客戶可能只需要每天發送電子郵件。 另一個人可能想要每個星期一和每一天。 但是我不能自動化代碼的schedule.every().monday/days部分,因為它們是方法而不是 arguments。

我知道我可以用幾個 if-else 語句做我想做的事。 但是隨着客戶及其需求的增長,硬編碼將變得無法維護。 你知道,這會很痛苦:

if report['day'] == 'monday':
    schedule.every().monday.at('03:00')...
elif report['day'] == 'tue':
    ...

天甚至不是這里唯一的一個參數。 那么,關於如何實現全自動系統的任何提示? 我可以提供您需要的任何其他信息。 謝謝你。

使用getattr function,您可以在獲取作業實例時進行一些自動化。

為方便起見,我插入了一些類型提示。

from typing import Literal, Optional

import schedule

UnitType = Literal["weeks", "days", "hours", "minutes", "seconds",
                   "week", "day", "hour", "minute", "second",
                   "monday", "tuesday", "wednesday", "thursday", 
                   "friday", "saturday", "sunday"]


def get_schedule_job(
        unit: UnitType,
        interval: int = 1,
        time: Optional[str] = None
) -> schedule.Job:
    schedule_job: schedule.Job = getattr(schedule.every(interval), unit)

    if time is not None:
        return schedule_job.at(time)
    return schedule_job


report_schedule_config_example = {
    "interval": 1,
    "unit": "monday",
    "time": "03:00"
}

get_schedule_job(**report_schedule_config_example).do(prepare_report)

您可以使用 Celery 和 Celery 節拍來完成此任務。

“Celery 是一個基於分布式消息傳遞的異步任務隊列/作業隊列。 它專注於實時操作,但也支持調度。”

您可以使用 celery 節拍周期性任務,根據間隔或 crontab 動態安排您的作業/任務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM