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

Django django-crontab定时任务仅手动命令生效,启动服务器无反应求助

Django定时任务(django-crontab)启动服务器后不执行问题排查

问题概述

配置了两个Django定时任务,手动执行python manage.py cron run时任务正常运行,但启动服务器后定时任务完全不触发。相关代码和配置如下:

定时任务代码

任务1:start_scraping

def start_scraping():
    prompts = Get_search_info()

    for prompt in prompts:

        stop = False
        category = prompt.category.link if prompt.category else "oferty"
        ignore_clone = prompt.just_created

        text = prompt.text.replace(" ", "-")
        link = f"https://www.olx.pl/{category}/q-{text}/"
        response = requests.get(link).text
        page_soup = BeautifulSoup(response, "html.parser")

        page_number = int(page_soup.find_all(attrs={"data-testid": "pagination-list-item"})[-1].text)
        for page in range(1, page_number + 1):
            if stop:
                break
            
            pagelink = f"{link}?page={page}"
            response = requests.get(pagelink).text
            page_soup = BeautifulSoup(response, "html.parser")
            cards = page_soup.find_all(attrs={"data-cy": "l-card"})
            cards_links = []

            for card in cards:
                card_url = card.find("a").get("href")
                if card_url not in cards_links and card.find(attrs={"data-testid": "adCard-featured"}) is None:
                    cards_links.append(f"https://www.olx.pl{card_url}")
                    print(card_url)

            is_exist = Add_new_link(cards_links, prompt.id)

            if is_exist and not ignore_clone:
                stop = True
        if prompt.just_created:
            change_created_status(prompt)

任务2:Run_bot(注:提供的代码与任务1函数名重复,需确认实际函数名)

def start_scraping():
    prompts = Get_search_info()

    for prompt in prompts:

        stop = False
        category = prompt.category.link if prompt.category else "oferty"
        ignore_clone = prompt.just_created

        text = prompt.text.replace(" ", "-")
        link = f"https://www.olx.pl/{category}/q-{text}/"
        response = requests.get(link).text
        page_soup = BeautifulSoup(response, "html.parser")

        page_number = int(page_soup.find_all(attrs={"data-testid": "pagination-list-item"})[-1].text)
        for page in range(1, page_number + 1):
            if stop:
                break
            
            pagelink = f"{link}?page={page}"
            response = requests.get(pagelink).text
            page_soup = BeautifulSoup(response, "html.parser")
            cards = page_soup.find_all(attrs={"data-cy": "l-card"})
            cards_links = []

            for card in cards:
                card_url = card.find("a").get("href")
                if card_url not in cards_links and card.find(attrs={"data-testid": "adCard-featured"}) is None:
                    cards_links.append(f"https://www.olx.pl{card_url}")
                    print(card_url)

            is_exist = Add_new_link(cards_links, prompt.id)

            if is_exist and not ignore_clone:
                stop = True
        if prompt.just_created:
            change_created_status(prompt)

settings.py配置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'OlxParserApp',
    'django_crontab',
]

CRONJOBS = [
    ('*/1 * * * *', 'OlxParserApp.cron.start_scraping'), 
    ('*/1 * * * *', 'OlxParserApp.cron.Run_bot'),  # Example task schedule
]

排查与解决步骤

1. 确认系统crontab服务状态

django-crontab依赖系统crond服务,先检查运行状态:

  • Debian/Ubuntu:sudo systemctl status cron
  • CentOS/RHEL:sudo systemctl status crond
    确保服务处于active (running)状态,未运行则启动并设置开机自启:
sudo systemctl start cron
sudo systemctl enable cron

2. 同步Django任务到系统crontab

启动Django服务器不会自动同步定时任务,必须手动执行:

python manage.py crontab add

执行后用crontab -l查看当前用户的crontab列表,确认是否包含Django任务条目。

3. 指定Python解释器路径(虚拟环境必做)

如果使用虚拟环境,需在settings.py中指定解释器路径,避免系统默认Python找不到依赖:

CRONTAB_PYTHON_EXECUTABLE = '/path/to/your/virtualenv/bin/python'

同时给任务添加日志重定向,方便排查错误:

CRONJOBS = [
    ('*/1 * * * *', 'OlxParserApp.cron.start_scraping', '>> /var/log/django_cron_start.log 2>&1'),
    ('*/1 * * * *', 'OlxParserApp.cron.Run_bot', '>> /var/log/django_cron_bot.log 2>&1'),
]

确保日志目录有写入权限。

4. 检查任务函数名正确性

第二个任务配置的是Run_bot,但提供的代码中函数名为start_scraping,需确认实际代码中是否存在Run_bot函数,避免因函数不存在导致任务失败。

5. 验证系统crontab基础功能

添加一个简单测试任务,确认系统crontab本身正常:

echo "*/1 * * * * echo 'test cron' >> /tmp/test_cron.log" | crontab -

等待1分钟后查看/tmp/test_cron.log,如果无内容则系统crontab存在配置问题,需排查系统层面的定时任务设置。

6. 核对用户权限

确保运行Django服务器的用户与crontab所属用户一致,避免因权限差异导致任务无法访问数据库或文件。

总结

按上述步骤逐一排查,核心要点:

  • 系统crond服务必须运行
  • 必须执行crontab add同步任务
  • 虚拟环境需指定正确的Python解释器
  • 任务函数名与配置一致
  • 通过日志定位具体报错

内容的提问来源于stack exchange,提问作者Ян Макотин

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:12:11