Cron in OpenCart 4.1 is built into the core. Tasks are stored in the cron table, the server's system scheduler runs cron.php once an hour, and the cron/cron controllerCode that receives a request and prepares data. More in the glossary → decides which tasks are due to run. OpenCart 3.0 has no such mechanism, so the module exposes its own token-protected route, which the server's crontab calls. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.
Why do modules need background tasks?
Some of a module's work should not run during a customer's request, because it is long, depends on a third-party API, or has to happen on a schedule regardless of visitors. Typical examples:
- updating the directory of cities and branches of Nova PoshtaThe most popular carrier in Ukraine. The integration usually pulls cities and branches through an API. More in the glossary → or UkrposhtaThe national postal operator; for remote settlements it is sometimes the only option. More in the glossary →;
- synchronizing stock and prices with an accounting system or a supplier's price list;
- generating feeds for marketplaces and advertising networks;
- checking the statuses of shipping waybills (TTN) and payments that did not arrive via callback;
- cleaning up the module's logs and cache.
If you do this "on the side" in a page controller, the first visitor after the interval expires will wait while the module downloads and parses several megabytes. Worse, with simultaneous requests the task will start several times in parallel. A background task runs in a separate process and does not affect storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → speed.
The data accumulated by such tasks usually lives in the module's own tables. This is described in the article module custom tables and migrations.
How is cron structured in OpenCart 4.1?
In 4.1 there is a cron table with the columns cron_id, code, description, cycle, action, status, date_added and date_modified. The action column holds the storefront controller route, and cycle holds the period: the value hour, day or month. In the admin they are displayed via the language strings text_hour, text_day and text_month. After installation, the table contains three core tasks: currency (currency rates, once a day), gdpr (processing data deletion requests) and subscription (disabled by default).
The main work is done by the storefront controller cron/cron:
catalog/ · OpenCart 4.1.0.4 · lines 14–28
public function index(): void {
$this->load->model('setting/cron');
$results = $this->model_setting_cron->getCrons();
$this->load->controller('cron/subscription', 3, 'subscription', 1, '', '');
foreach ($results as $result) {
if ($result['status'] && (strtotime('+1 ' . $result['cycle'], strtotime($result['date_modified'])) < (time() + 10))) {
$this->model_setting_cron->editCron($result['cron_id']);
$this->load->controller($result['action'], $result['cron_id'], $result['code'], $result['cycle'], $result['date_added'], $result['date_modified']);
}
}
}
Several points important for modules follow from this code:
- The schedule is counted from the last run. A task with
dayruns when more than a day (with a 10-second margin) has passed sincedate_modified. You cannot set an exact time of day, because it drifts along with the first run. - The mark is set before execution.
editCron()updatesdate_modifiedbefore calling the controller. If the task fails, the next attempt will only happen after a full cycle. The module must organize retries after errors by itself. - The controller receives five arguments:
$cron_id,$code,$cycle,$date_added,$date_modified. This is how the built-in taskscron/currencyandcron/gdprare structured. - All tasks run sequentially in one process. A long task delays all the following ones.
Note line 19: in 4.1.0.4, cron/subscription is called on every run, regardless of the status and schedule of the subscription task in the table.
flowchart TD
A["crontab сервера, щогодини"] --> B["php cron.php"]
B --> C["стартові дії вітрини: setting, language, extension, event"]
C --> D["cron/cron: усі задачі з таблиці cron"]
D --> E{"status = 1 і минув цикл?"}
E -- "ні" --> F["пропустити"]
E -- "так" --> G["editCron: date_modified = NOW()"]
G --> H["контролер з колонки action"]
How do you run cron 4.1 on the server?
There are two entry points, and both lead to the same cron/cron.
CLI: cron.php
The store root contains cron.php. It includes config.php via a relative path, builds the storefront registry, performs the startup actions from action_pre_action in system/ (settings, language, extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary →, events) and calls cron/cron. Because of the relative path, the script must be run from the store directory:
Example
# crontab -e: щогодини, на початку години
0 * * * * cd /var/www/shop/public_html && /usr/bin/php cron.php >> /var/www/shop/cron.log 2>&1
We recommend running cron every hour: tasks from hour then run on time, while day and month are accurate to the hour. The tasks page in the admin does not suggest a run frequency; it only shows an example address index.php?route=cron/. In CLI mode PHP does not limit execution time by default, so max_execution_time will not interrupt long synchronizations.
HTTP: index.php?route=cron/cron
The admin also shows an address of the form https:// for hosts where only a URL can be configured. Such a request goes through the regular index.php, so web server limits apply to it: the PHP-FPM and proxy timeouts, max_execution_time. The route is not protected in any way, so anyone can call it. The schedule will not let a task run more often than its cycle, but whoever opens the address determines the moment of the run. If you have CLI access, use cron.php.
Tasks are visible under "Extensions → Cron Jobs". There you can also disable, delete, or run them manually with a button. A manual run from the admin creates a storefront instance and, unlike cron/cron, updates date_modified only after execution.

How does a module register its own task in 4.1?
The task is added to the install() table of the module through the admin model setting/cron and removed in uninstall(). The signature in 4.1.0.4 is: addCron(string $code, string $description, string $cycle, string $action, bool $status): int. It is deleted by code via deleteCronByCode(string $code).
Example
// extension/mymodule/admin/controller/module/mymodule.php
public function install(): void {
$this->load->model('setting/cron');
$this->model_setting_cron->deleteCronByCode('mymodule_sync');
$this->model_setting_cron->addCron('mymodule_sync', 'Mymodule: синхронізація залишків', 'hour', 'extension/mymodule/cron/sync', true);
}
public function uninstall(): void {
$this->load->model('setting/cron');
$this->model_setting_cron->deleteCronByCode('mymodule_sync');
}
The action route points to the storefront controller, that is, the file extension/. Storefront namespaces are registered only for extensions present in the extension table, so the task of a module that is not installed will not find its controller.
Example
<?php
namespace Opencart\Catalog\Controller\Extension\Mymodule\Cron;
class Sync extends \Opencart\System\Engine\Controller {
public function index(int $cron_id, string $code, string $cycle, string $date_added, string $date_modified): void {
if (!$this->config->get('module_mymodule_status')) {
return;
}
$this->load->model('extension/mymodule/module/mymodule');
$this->model_extension_mymodule_module_mymodule->syncStock();
}
}
Start the task code with the module code, and always delete the old task by code before addCron(). The core does not check the uniqueness of code, so reinstalling would otherwise create a duplicate, and the synchronization would run twice per cycle. The order of installation and removal is described in the article module install and uninstall.
How do you run background tasks in OpenCart 3.0?
In 3.0.4.1 and 3.0.5.1 there is neither a cron table, nor cron.php, nor a tasks page. The most reliable workaround uses exactly the 3.0 core for the Square payment module. The admin generates a secret payment_squareup_cron_token and shows a ready-made address index.php?route=extension/, and the storefront runs the task only when the token matches the setting.
For your own module, the scheme is as follows:
- When saving settings, generate a token if there isn't one yet, for example
bin2hex(random_bytes(16)), and store it under themodule_mymodule_cron_tokenkey. - Add a controller method to the storefront, for example the route
extension/, which checks the token and runs the task.module/ mymodule/ cron - Show the administrator a ready-made line for crontab in the module form.
Example
// OpenCart 3.0: catalog/controller/extension/module/mymodule.php
public function cron() {
$token = isset($this->request->get['token']) ? (string)$this->request->get['token'] : '';
if (!$this->config->get('module_mymodule_status') || !$this->config->get('module_mymodule_cron_token') || !hash_equals((string)$this->config->get('module_mymodule_cron_token'), $token)) {
$this->response->addHeader('HTTP/1.1 403 Forbidden');
return;
}
set_time_limit(0);
$this->load->model('extension/module/mymodule');
$this->model_extension_module_mymodule->syncStock();
$this->response->setOutput('OK');
}
Example
15 * * * * curl -fsS "https://shop.example/index.php?route=extension/module/mymodule/cron&token=ТОКЕН" > /dev/null
Use hash_equals() to compare tokens, not ==, and do not accept an empty token. Otherwise a module without settings would run the task for anyone. A route with a method in 3.0 is written with a slash, not a dot. For more details, see the article routing with route= in OpenCart.
Another option for 3.0 is called "pseudo-cron": an event after on the storefront controller checks the time of the last run and, if needed, executes a short task. It works without access to crontab, but the task runs inside a visitor's request and only when someone visits the site. Also keep in mind that in 3.0 the value returned by an after handler replaces the controller output, so the handler must not return anything. Use this path only for light actions, such as cleaning up old records.
How do you make a task reliable?
Regardless of version, a background task must survive failures, parallel runs and large volumes of data.
- Locking against parallel runs. A run from the admin, from crontab and over HTTP can coincide. Set a lock, for example
GET_LOCK('mymodule_sync', 0)in MySQL or a lock file instoragewithflock(), and exit if it is already taken. - Idempotency. A repeated run must not duplicate orders, emails or waybills. Mark processed records and check the mark before acting.
- Batches. Process data in parts and store a cursor. Then an interrupted run continues from where it stopped.
- Log. Write the result to
$thisor to your own table: time, number of processed records, API errors. Without a log you cannot explain to a client why stock was not updated.->log ->write() - Module status. The task should first check whether the module is enabled. In 4.1, a disabled module does not remove the task from the
crontable, and in 3.0 crontab will keep calling the address. - Time zone.
cron.phpsets the time zone from thedate_timezoneconfig, whileNOW()in MySQL depends on the database server settings. Compare times within one system so the task does not run an hour earlier or later.
The structure of the module in which these controllers and models live is described in the article anatomy of an OpenCart extension.
Summary
- OpenCart 4.1: tasks are stored in the
crontable, crontab runscron.phphourly, andcron/cronexecutes tasks whose cyclehour,dayormonthhas elapsed. - A module registers a task via
addCron()ininstall(), removes it viadeleteCronByCode(), and the action route leads to the storefront controller with five arguments. - OpenCart 3.0: there is no scheduler. Build a storefront route with a secret token and call it from crontab, as the core does for Square.
- Any background task should have locking, process data in batches, keep a log, and check the module status as the first step.
Other topics in this section are collected on the page creating extensions for OpenCart.