Execute a cron job from a method using python in odoo 12

2k Views Asked by At

I'd like to execute a Cron Job at the end of the method execution when I click a button, I read this post which mention to explicitly run a method, but it isn't working for me.

So far this is what I got:

my cron job

 <record id="ir_cron_save_timesheets" model="ir.cron">
            <field name="name">Save timesheets</field>
            <field name="model_id" ref="rw_project.model_rw_file_reader"/>
            <field name="type">ir.actions.server</field>
            <field name="state">code</field>
            <field name="code">model.process_ts()</field>
            <field name="interval_number">1</field>
            <field name="interval_type">days</field>
            <field name="numbercall">-1</field>
        </record>

in the button code at the end I want to execute this:

self.env.ref('project_name.ir_cron_save_timesheets').process_ts()

In the model, I do have a method name called process_ts

the error that I'm getting is:

AttributeError: 'ir.cron' object has no attribute 'process_ts'

If I remove process_ts it doesn't get executed

2

There are 2 best solutions below

2
On BEST ANSWER

You are trying to call process_ts on a cron record which is wrong, the process_ts method is defined in the rw_project.model_rw_file_reader model.

You have just to call the method_direct_trigger() and it should call the process_ts() method:

self.env.ref('project_name.ir_cron_save_timesheets').method_direct_trigger()
0
On

From my own experience, It does not seem interesting to trigger a cron from python, because - as Kenly said previouly - the UI remains spining, waiting for the cron-process to get completed ... because it does not run in another thread. and a pythonic solution is still missing.

The best and easiest way to get an asynchronous job in Odoo, would be to call your method process_ts() using a button related to an ajax/rpc (+Promise) in javascript.