You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Odoo中Cron任务运行异常:每分钟天气获取任务失效求助

Hey there! Let's tackle your Odoo cron issue step by step, and also cover how cron jobs work in Odoo.

First: Fixing Your Weather Cron Job

Looking at your code and config, here are the key issues preventing your cron from running, plus fixes:

1. Your Cron is Disabled

In your XML config, the active field is set to eval="False" — this means the cron job is turned off by default. Change it to eval="True" to enable it:

<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<data noupdate="1">
<record forcecreate="True" id="create_weather_info_cron" model="ir.cron">
<field name="name">Weather Information</field>
<field name="user_id" ref="base.user_root"/>
<field name="active" eval="True" /> <!-- Enable the cron job -->
<field name="interval_number">1</field>
<field name="interval_type">minutes</field>
<field name="numbercall">-1</field>
<field name="doall" eval="False"/>
<field name="model" eval="'weather_location.weather_location'"/>
<field name="function" eval="'weather_cron'"/>
</record>
</data>
</odoo>

2. Add Error Handling & Robustness

Your Python function has no error handling — if the API request fails, returns invalid JSON, or missing fields, the entire cron will crash silently. Here's a revised version with safety checks:

import requests
from odoo import models, api
from odoo.exceptions import UserError

class WeatherLocation(models.Model):
    _name = 'weather_location.weather_location'
    _description = 'Weather Location'

    @api.model
    def weather_cron(self):
        weather_location_ids = self.search([])
        for weather_location_id in weather_location_ids:
            url_cron = weather_location_id.api_address + weather_location_id.name
            try:
                # Add timeout to avoid hanging requests
                response = requests.get(url_cron, timeout=10)
                response.raise_for_status()  # Catch HTTP errors (4xx/5xx)
                json_data = response.json()

                # Validate required JSON fields exist
                if not json_data.get('weather') or not json_data['weather']:
                    raise ValueError("No weather data found in API response")
                if 'main' not in json_data:
                    raise ValueError("Missing temperature/humidity data in API response")

                # Extract data safely
                formatted_data = json_data['weather'][0]['main']
                formatted_data1 = json_data['main']['temp']
                formatted_data2 = json_data['main']['temp_min']
                formatted_data3 = json_data['main']['temp_max']
                formatted_data4 = json_data['main']['humidity']

                self.env['current_weather.current_weather'].create({
                    'weather_id': weather_location_id.id,
                    'main': formatted_data,
                    'temp': formatted_data1,
                    'temp_min': formatted_data2,
                    'temp_max': formatted_data3,
                    'humidity': formatted_data4,
                })
            except requests.exceptions.RequestException as e:
                # Log request errors instead of crashing the cron
                self.env['ir.logging'].create({
                    'name': 'Weather Cron Request Error',
                    'type': 'server',
                    'message': f"Failed to fetch weather for {weather_location_id.name}: {str(e)}",
                    'level': 'error',
                })
            except (KeyError, ValueError) as e:
                # Log invalid data errors
                self.env['ir.logging'].create({
                    'name': 'Weather Cron Data Error',
                    'type': 'server',
                    'message': f"Invalid data for {weather_location_id.name}: {str(e)}",
                    'level': 'error',
                })

3. Ensure Dependencies Are Met

Make sure your module depends on the requests library. Add it to your module's __manifest__.py:

{
    'name': 'Weather Integration',
    'depends': ['base', 'requests'],  # Add 'requests' here
    # ... other manifest fields
}

How to Run Cron Jobs in Odoo

Odoo handles cron jobs in two main ways:

1. Automatic Scheduled Runs

Odoo's built-in cron service checks for pending jobs every minute by default. Once your cron is enabled (active=True), it will run automatically based on your interval settings (every minute in your case).

2. Manual Triggering

If you want to test your cron immediately, you have two options:

  • Via UI: Go to Settings > Technical > Automation > Scheduled Actions, find your "Weather Information" cron, and click the Run Manually button.
  • Via Code: Call the cron directly from an Odoo shell or another function:
    # Replace with your cron's ID
    self.env['ir.cron'].browse(your_cron_id).method_direct_trigger()
    

3. Check Cron Logs

To debug why a cron isn't running, check the logs:

  • Go to Settings > Technical > Logs > Cron Logs to see execution history, success status, and error messages.
  • Check your Odoo server logs (usually in the log directory) for detailed tracebacks.

After making these changes, upgrade your module to apply the updates, and your cron should start running as expected.

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

火山引擎 最新活动