# Cron in OpenCart: module background tasks in 4.1 and workarounds in 3.0

> How cron works in OpenCart 4.1: the cron table, cron.php and cron/cron, and registering a task from a module. And how to run background tasks in 3.0, where there is no scheduler.

Джерело: https://opencartcode.com/en/wiki/dev-extensions/cron-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

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` [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) 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 Poshta](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#nova-poshta) or [Ukrposhta](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#ukrposhta);
- 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 [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) 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](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-tables).

## 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/controller/cron/cron.php` · OpenCart 4.1.0.4 · lines 14–28

```php
	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 `day` runs when more than a day (with a 10-second margin) has passed since `date_modified`. You cannot set an exact time of day, because it drifts along with the first run.
- **The mark is set before execution.** `editCron()` updates `date_modified` before 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 tasks `cron/currency` and `cron/gdpr` are 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.

```mermaid
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/config/catalog.php` (settings, language, [extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions), events) and calls `cron/cron`. Because of the relative path, the script must be run from the store directory:

Example

```bash
# 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/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://магазин/index.php?route=cron/cron` 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.

«Розширення → Заплановані завдання»: код, цикл, маршрут дії і кнопка запуску · OpenCart 4.1.0.4

## 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

```php
// 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/mymodule/catalog/controller/cron/sync.php`. 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
<?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](https://opencartcode.com/en/wiki/dev-extensions/install-opencart-module).

## 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/recurring/squareup/recurring&cron_token=...`, and the storefront runs the task only when the token matches the setting.

For your own module, the scheme is as follows:

1. When saving settings, generate a token if there isn't one yet, for example `bin2hex(random_bytes(16))`, and store it under the `module_mymodule_cron_token` key.
2. Add a controller method to the storefront, for example the route `extension/module/mymodule/cron`, which checks the token and runs the task.
3. Show the administrator a ready-made line for crontab in the module form.

Example

```php
// 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

```bash
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](https://opencartcode.com/en/wiki/dev-mvc/opencart-route).

> Running via HTTP is limited by web server timeouts, so `set_time_limit(0)` only helps partially. Process large volumes in batches: for example, 500 products per call, and keep the position in `setting` or in your own table.

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 in `storage` with `flock()`, 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 `$this->log->write()` or 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.
- **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 `cron` table, and in 3.0 crontab will keep calling the address.
- **Time zone.** `cron.php` sets the time zone from the `date_timezone` config, while `NOW()` 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](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure).

## Summary

- OpenCart 4.1: tasks are stored in the `cron` table, crontab runs `cron.php` hourly, and `cron/cron` executes tasks whose cycle `hour`, `day` or `month` has elapsed.
- A module registers a task via `addCron()` in `install()`, removes it via `deleteCronByCode()`, 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](https://opencartcode.com/en/wiki/dev-extensions).

## FAQ

**What to do if your hosting doesn't let you set up crontab?**

Use an external service that opens the URL on a schedule: in 4.1 it's the cron/cron address, in 3.0 it's the module's route with a token. Long tasks must then be split into batches to fit HTTP timeouts.

**Can you set a task to run every 15 minutes in 4.1?**

Not out of the box: cron.php is designed to run hourly, and the shortest cycle in the admin is one hour. For more frequent tasks, add a separate crontab line that calls your route directly.

**How do you test a 4.1 task without waiting for the cycle?**

Click the run button next to the task in «Extensions → Scheduled Tasks». The task will run immediately, and the last run time will update.

**Why doesn't the 4.1 task run even though crontab is working?**

Check the task status, the date of the last run, and whether the module is installed in «Extensions → Extensions». Without installation, the controller namespace isn't registered and the action route can't be found.
