繁体   English   中英

python安排不同时区的作业

[英]python schedule jobs with different timezones

我想安排一个 python 函数每天在特定时间为具有不同时区的客户列表运行。

这基本上就是我想要做的:

import schedule
import time

def job(text):
    print("Hello " + text)

def add_job(user_tz, time, text):
    schedule.every().day.at(time).do(job(text)) 
    # the above adds all jobs at local time, I want to use different timezones with these

def run_job():
    while(1):
        schedule.run_pending()
        time.sleep(1)

if __name__=='__main__':
    add_job('America/New_York', "12:00", 'New York')
    add_job('Europe/London', "12:00", 'London')
    run_job()

我正在使用它来使用烧瓶和外部 API 发布/接收一些东西。

Celery 或 heroku 调度程序或一些沉重的东西不是我正在寻找的东西,debian(或 nix)env 的轻量级和 pythonic 的东西将是理想的。 我研究了schedulertzcronAPScheduler ,但无法弄清楚我们如何将它们与时区一起使用。

此外,我尝试使用 crontab,但无法弄清楚如何在运行时添加作业,因为我也希望能够在运行时使用上述函数添加/删除作业。

我对 python 有一些经验,但这是我的第一个问题时区,我对此知之甚少,所以如果我遗漏了什么或有任何其他方法,请随时启发我。

谢谢!

箭头库对此非常有用,并且比标准日期/时间 (imo) 简单得多。 箭头文档

import arrow
from datetime import datetime

now = datetime.now()
atime = arrow.get(now)
print(now)
print (atime)

eastern = atime.to('US/Eastern')
print (eastern)
print (eastern.datetime)

2017-11-17 09:53:58.700546
2017-11-17T09:53:58.700546+00:00
2017-11-17T04:53:58.700546-05:00
2017-11-17 04:53:58.700546-05:00

我会更改您的“add_job”方法,将所有传入日期修改为标准时区(例如 utc)。

所描述的问题听起来像 python 的调度程序库提供了一个开箱即用的解决方案,不需要用户进一步定制。 调度程序库被设计成可以在不同的时区调度作业,它与调度程序创建的时区以及作业调度的独立时区无关。

披露:我是调度程序库的作者之一

为了演示,我将文档中示例改编为问题:

import datetime as dt
from scheduler import Scheduler
import scheduler.trigger as trigger

# Create a payload callback function
def useful():
    print("Very useful function.")

# Instead of setting the timezones yourself you can use the `pytz` library
tz_new_york = dt.timezone(dt.timedelta(hours=-5))
tz_wuppertal = dt.timezone(dt.timedelta(hours=2))
tz_sydney = dt.timezone(dt.timedelta(hours=10))

# can be any valid timezone
schedule = Scheduler(tzinfo=dt.timezone.utc)

# schedule jobs
schedule.daily(dt.time(hour=12, tzinfo=tz_new_york), useful)
schedule.daily(dt.time(hour=12, tzinfo=tz_wuppertal), useful)
schedule.daily(dt.time(hour=12, tzinfo=tz_sydney), useful)

# Show a table overview of your jobs
print(schedule)
max_exec=inf, tzinfo=UTC, priority_function=linear_priority_function, #jobs=3

type     function         due at              tzinfo          due in      attempts weight
-------- ---------------- ------------------- ------------ --------- ------------- ------
DAILY    useful()         2021-07-20 12:00:00 UTC-05:00      1:23:39         0/inf      1
DAILY    useful()         2021-07-21 12:00:00 UTC+10:00     10:23:39         0/inf      1
DAILY    useful()         2021-07-21 12:00:00 UTC+02:00     18:23:39         0/inf      1

使用简单的循环执行作业:

import time
while True:
    schedule.exec_jobs()
    time.sleep(1)  # wait a second

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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