美文网首页
celery中的时区陷阱

celery中的时区陷阱

作者: luckriver | 来源:发表于2019-05-07 17:28 被阅读0次

    Django中使用celery执行异步任务非常方便,通过apply_async可以控制定时任务的执行时间。一般使用场景中,比较多的是任务在一定时间之后执行,这时只要指定countdown参数就可以了,eta参数能够指定任务执行的绝对时间,由于在项目中使用很少,因此一些特性之前没注意到。

    eta默认为UTC时间

    假设在celery 4.x 版本中定义如下任务

    @app.task(queue='celery')
    def hello():
        print '==========='
        print 'hello world'
        print '==========='
    

    调用hello.apply_async(eta=datetime.datetime.now())时任务不会立即执行,实际情况是过8小时之后才会执行。查了celery源码,发现eta参数在消费者也就是web server发消息时基本会直接设置在amqp消息中,默认为UTC时间。

    if countdown:  # convert countdown to ETA
        self._verify_seconds(countdown, 'countdown')
        now = now or self.app.now()
        eta = now + timedelta(seconds=countdown)
    if isinstance(expires, numbers.Real):
        self._verify_seconds(expires, 'expires')
        now = now or self.app.now()
        expires = now + timedelta(seconds=expires)
    eta = eta and eta.isoformat()
    

    当worker收到消息后,会根据本地的时区信息将UTC转换为本地时间进行执行
    其中to_system_tz就是转换为系统也即本地时间

    if req.utc:
        eta = to_timestamp(to_system_tz(req.eta))
    else:
        eta = to_timestamp(req.eta, app.timezone)
    

    countdown 为什么没问题

    由上面代码可以看出,countdown也会转换为eta存储在消息中,而countdown之所以没问题,是因为基本时间即now为UTC时间。

    celery时区相关配置

    celery中和时区相关的配置主要有[两个]

    • CELERY_ENABLE_UTC 开启后消息的时间将会按照UTC时区转化,默认开启
    • ** CELERY_TIMEZONE** 默认为UTC,可以是任何[pytz]支持的时区

    设置本地时区并不能解决上面的问题,因为eta就没有进行过时区转换,完全是按照用户传进来的时间进行计算

    解决方法

    可以采用下面的代码进行解决,时区为Asia/Shanghai

    import datetime
    from django.utils.timezone import get_current_timezone
    
    n = datetime.datetime.now()
    tz = get_current_timezone()
    n = tz.localize(n)
    hello.apply_async(eta=n)
    

    需要注意的是通过n.replace(tzinfo=tz)进行替换的话,总是会和期望的时间相差6分钟,而这又是另外一个问题。pytz中上海时间比北京时间提前了6分钟。。。

    相关文章

      网友评论

          本文标题:celery中的时区陷阱

          本文链接:https://www.haomeiwen.com/subject/eweyoqtx.html