You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Celery周期性任务完全未执行,寻求解决方案

问题排查与修复方案

1. 修复任务函数参数错误

Celery任务函数不是类方法,不需要self参数,这个错误会导致任务执行时参数不匹配直接失败。修改tasks.py中的handle函数:

@app.task
def handle(*args, **kwargs):  # 移除self参数
    feeds = Feed.objects.all()
    for feed in feeds:
        new_list = feedparser.parse(feed.url)
        for entry in new_list.entries:
            start = datetime.now(timezone.utc)
            end = datetime(*(entry.published_parsed[0:6])).replace(tzinfo=timezone.utc)
            if (start - end).days < 2 and not Article.objects.filter(url=entry.link).exists():
                article = Article()
                article.title = entry.title
                article.url = entry.link
                article.description = entry.description
                # 直接赋值datetime对象给DateTimeField,无需转字符串
                article.publication_date = end
                article.save()

2. 修正日期字段赋值逻辑

Django的DateTimeField字段直接接受datetime对象,不需要转成字符串。之前的字符串转换会导致日期存储失败或格式错误,删除字符串转换步骤,直接赋值end对象。

3. 确保Beat与Worker正确协同运行

  • 单独启动Worker:celery -A mysite worker -l INFO
  • 单独启动Beat:celery -A mysite beat -l INFO(加上-l INFO查看调度日志,确认任务是否被定时触发)
  • 或者用一个命令同时启动两者:celery -A mysite worker -l INFO -B

4. 关键排查步骤

  • 检查Redis服务是否正常运行:确保本地Redis服务已启动,Celery能连接到redis://地址(默认是localhost:6379)。
  • 查看Worker日志:运行Worker时用-l DEBUG级别,查看任务执行时的具体报错,比如数据库连接异常、feedparser解析失败等。
  • 测试Feed解析:在Django shell中执行feedparser.parse(feed.url),确认能正常获取到entries数据,排除Feed URL无效的问题。
  • 验证Celery配置:在settings.py中添加明确的Celery配置,避免隐式配置问题:
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'rpc://'
CELERY_TIMEZONE = 'UTC'

内容的提问来源于stack exchange,提问作者szyle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:06:25