|
| 1 | +# Copyright (c) 2026 ACSONE SA/NV (<http://acsone.eu>) |
| 2 | +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) |
| 3 | + |
| 4 | +import logging |
| 5 | + |
| 6 | +from odoo import api, models |
| 7 | + |
| 8 | +from ..controllers.main import RunJobController |
| 9 | +from ..job import Job |
| 10 | + |
| 11 | +_logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class QueueJobExecutor(models.AbstractModel): |
| 15 | + _name = "queue.job.executor" |
| 16 | + _description = "Queue Job Executor" |
| 17 | + |
| 18 | + @api.model |
| 19 | + def _executor_cron_domain(self) -> list: |
| 20 | + model_id = self.env["ir.model"]._get("queue.job.executor").id |
| 21 | + return [ |
| 22 | + ("model_id", "=", model_id), |
| 23 | + ("state", "=", "code"), |
| 24 | + ("code", "=", "model._execute_ready_jobs()"), |
| 25 | + ] |
| 26 | + |
| 27 | + @api.model |
| 28 | + def _ensure_executor_crons(self, capacity: int) -> None: |
| 29 | + """Since Odoo cron can't run cron jobs in parallel, we create several. |
| 30 | +
|
| 31 | + `capacity` should be equal to the root channel capacity. If it's more, |
| 32 | + it's wasteful. If it's less, job will stay in ENQUEUED state longer than |
| 33 | + needed and loop back to PENDING due to the dead jobs requeuer. |
| 34 | + """ |
| 35 | + if capacity < 1: |
| 36 | + return |
| 37 | + ref_cron = self.env.ref("queue_job.queue_job_executor_cron") |
| 38 | + ref_cron.active = True |
| 39 | + # remove clones |
| 40 | + self.env["ir.cron"].with_context(active_test=False).search( |
| 41 | + self._executor_cron_domain() + [("id", "!=", ref_cron.id)] |
| 42 | + ).unlink() |
| 43 | + # re-create desired number of clones |
| 44 | + for _i in range(1, capacity): |
| 45 | + ref_cron.copy() |
| 46 | + |
| 47 | + @api.model |
| 48 | + def _enable_executor_cron(self, capacity: int) -> None: |
| 49 | + self._ensure_executor_crons(capacity) |
| 50 | + self.env["ir.config_parameter"].set_param("queue_job.run_as", "cron") |
| 51 | + |
| 52 | + @api.model |
| 53 | + def _execute_job(self, job: Job) -> None: |
| 54 | + RunJobController._runjob(self.env, job) |
| 55 | + |
| 56 | + @api.model |
| 57 | + def _execute_ready_jobs(self) -> None: |
| 58 | + while job := RunJobController._acquire_job(self.env): |
| 59 | + _logger.debug("executor cron running queue job %s", job.uuid) |
| 60 | + self._execute_job(job) |
0 commit comments