Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Reports and Integration

Automated Actions, Cron Jobs and Email

Automate Odoo: scheduled actions with ir.cron, server actions, automation rules, email templates and the mail thread with chatter, plus runnable scheduler and template stand-ins.

Business software must do things on its own: send a reminder three days before a due date, close stale tickets every night, notify a manager when a big order is confirmed. Odoo has four tools for this, and choosing the right one keeps your module simple.

Tool Triggered by Typical use
Scheduled action (ir.cron) The clock Nightly jobs, reminders
Server action (ir.actions.server) A button, a menu or an automation One reusable operation
Automation rule (base.automation) A record is created, updated, deleted or hits a time condition Low-code reactions
Mail template (mail.template) Called from code or an action Emails with placeholders

The real server cannot run here. Odoo code is read-only; the stand-ins model the scheduler and the template rendering.

Scheduled actions

A cron is a record that says "call this Python method every N minutes, hours or days":

XML
<record id="cron_library_overdue" model="ir.cron">
  <field name="name">Library: notify overdue loans</field>
  <field name="model_id" ref="model_library_loan"/>
  <field name="state">code</field>
  <field name="code">model._cron_notify_overdue()</field>
  <field name="interval_number">1</field>
  <field name="interval_type">days</field>
  <field name="active" eval="True"/>
</record>
Python
class LibraryLoan(models.Model):
    _inherit = "library.loan"

    @api.model
    def _cron_notify_overdue(self):
        overdue = self.search([("state", "=", "open"),
                               ("date_due", "<", fields.Date.today())])
        template = self.env.ref("library.mail_template_overdue")
        for loan in overdue:
            template.send_mail(loan.id)

Details that matter:

  • The method runs with superuser rights (OdooBot), so decide deliberately which records it touches.
  • Odoo processes jobs with worker processes; if one run is still going, the next waits. Jobs are time-limited, so long work should handle batches and reschedule itself (self.env.ref("module.cron_id")._trigger()).
  • Commit after each batch in large jobs so a failure doesn't roll back everything. Recent versions provide a progress helper that does this for you.
  • nextcall is stored, and a cron is not a precise clock: expect minutes of slack.
  • In development, you can click Run Manually in Settings, Technical, Scheduled Actions.

Server actions

A server action is a stored operation of a few kinds: execute Python code, update a record, create a record, send an email or run several actions.

XML
<record id="action_mark_lost" model="ir.actions.server">
  <field name="name">Mark as lost</field>
  <field name="model_id" ref="model_library_book"/>
  <field name="binding_model_id" ref="model_library_book"/>
  <field name="state">code</field>
  <field name="code">records.write({"state": "lost"})</field>
</record>

binding_model_id puts the action in the form's Action menu. Inside the code the variables records, record, env, model, time, datetime, log and UserError are available. The code runs in a restricted evaluator, so import statements are not allowed. Complicated logic belongs in a model method that the action merely calls.

Automation rules

base.automation (the Automation app, once a separate module) fires server actions on triggers: on creation, on update of a field, on deletion, on a time condition ("3 days after the due date"), or on a form change. It is excellent for administrators and quick prototypes. Developers should prefer code in the model for core logic, because rules hidden in the database are hard to review and test.

Email templates

XML
<record id="mail_template_overdue" model="mail.template">
  <field name="name">Library: overdue notice</field>
  <field name="model_id" ref="model_library_loan"/>
  <field name="subject">Your loan {{ object.name }} is overdue</field>
  <field name="email_to">{{ object.member_id.email }}</field>
  <field name="body_html" type="html">
    <p>Hello <t t-out="object.member_id.name"/>, your book is due since
       <t t-out="object.date_due"/>.</p>
  </field>
</record>

Subject and addresses use inline expressions in double braces; the HTML body uses QWeb. From code: template.send_mail(record.id, force_send=True) renders and sends (or queues) the email. Odoo puts outgoing mails in mail.mail, sent by the Mail: Email Queue Manager cron, which is why a missing outgoing mail server shows up as emails stuck in the queue.

The mail thread and chatter

Inheriting mail.thread gives a model its chatter: the message log, followers and attachments, plus message_post. Inheriting mail.activity.mixin adds scheduled activities ("Call customer on Friday").

Python
class LibraryLoan(models.Model):
    _name = "library.loan"
    _inherit = ["mail.thread", "mail.activity.mixin"]

    state = fields.Selection([("open", "Open"), ("returned", "Returned")],
                             tracking=True)       # changes are logged in chatter

    def action_return(self):
        self.write({"state": "returned"})
        self.message_post(body="Book returned", subtype_xmlid="mail.mt_note")

tracking=True writes a line to the chatter whenever the field changes, which gives you an audit trail for free.

A cron scheduler stand-in

This stand-in keeps a list of jobs with an interval, computes which ones are due at a given time and runs them, advancing nextcall like ir.cron does.

Python Schedule and run jobs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A mail template stand-in

The template renderer substitutes {{ ... }} placeholders from a record, like the inline syntax of mail.template. The stand-in only supports simple dotted paths and does not evaluate arbitrary code.

Python Render an email from a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Which tool should you use?

  • Fixed schedule, owned by the developer: cron calling a model method.
  • A reusable operation attached to a button or menu: server action.
  • An administrator wants "when X happens, do Y" without code: automation rule.
  • Any text that goes to a person: mail template, rendered per record, with translations.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which model stores scheduled actions?

    ir.cron records hold the method to call, the interval and the next call time.
  2. 2. What does tracking=True on a field do?

    Tracked fields are logged in the chatter, giving an audit trail of value changes.
  3. 3. Why should a long cron job work in batches?

    Jobs have time limits and share workers, so batches with commits and re-triggering are safer.
  4. 4. Which mixin gives a model chatter, followers and message_post?

    Inherit mail.thread to get the message log and followers.

Summary

  • ir.cron runs a method on a schedule, with superuser rights and time limits.
  • Server actions package reusable operations; automation rules react to events without code.
  • Mail templates render subject, recipients and body per record; mails go through a queue.
  • mail.thread adds chatter; tracking=True records field changes.
  • Prefer model methods for real logic and keep records of automation small.

Next: Configuration and Deployment