Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.5']
php: ['8.1', '8.2', '8.3', '8.4', '8.5']
steps:
- name: Checkout
uses: actions/checkout@v7
Expand Down
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@

Опорные файлы: `README.md`, `.github/CONTRIBUTING.md`.

`composer.json`: triangle/cron; runtime "^8.1"; triangle/engine.
`composer.json`: triangle/cron; runtime `^8.1`; Engine `^9.0`; Localzet Cron `^2.0`.

Именованных test/lint/build-скриптов в проверенных JSON-манифестах нет. Перед запуском выбери существующую команду из CI, конфигурации тестов или Makefile; не выдавай предполагаемую команду за проверенную.
Проверки: `composer run lint`, `composer run test`, `composer run check`. CI дополнительно выполняет `composer validate` и проверяет PHP 8.1–8.5.

Команды выше найдены в манифестах, а не проверены запуском. Перед выполнением прочитай их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test.
Команды проверок перечислены в манифесте и CI. Перед запуском изучи их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test.

### Ограничения реализации

Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed
- Prepare the Engine 9 and Localzet Server 7 compatibility release.
- Require `triangle/engine:^9.0` and `localzet/cron:^2.0`.

### Removed
- Remove the unused `triangle/events` dependency.

### Migration
- This release line requires Engine 9 and Localzet Server 7; Engine 8 and Server 4 applications must remain on `triangle/cron` 1.x.

### Planned
- Task queuing
- Distributed task execution
Expand Down
78 changes: 57 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,57 @@
<p align="center"><a href="https://www.localzet.com" target="_blank">
<img src="https://static.zorin.space/media/logos/LocalzetGroup.png" width="400">
</a></p>

<p align="center">
<a href="https://packagist.org/packages/triangle/cron">
<img src="https://img.shields.io/packagist/dt/triangle/cron?label=%D0%A1%D0%BA%D0%B0%D1%87%D0%B8%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F" alt="Скачивания">
</a>
<a href="https://github.com/Triangle-org/Cron">
<img src="https://img.shields.io/github/commit-activity/t/Triangle-org/Cron?label=%D0%9A%D0%BE%D0%BC%D0%BC%D0%B8%D1%82%D1%8B" alt="Коммиты">
</a>
<a href="https://packagist.org/packages/triangle/cron">
<img src="https://img.shields.io/packagist/v/triangle/cron?label=%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F" alt="Версия">
</a>
<a href="https://packagist.org/packages/triangle/cron">
<img src="https://img.shields.io/packagist/dependency-v/triangle/cron/php?label=PHP" alt="Версия PHP">
</a>
<a href="https://github.com/Triangle-org/Cron">
<img src="https://img.shields.io/github/license/Triangle-org/Cron?label=%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F" alt="Лицензия">
</a>
</p>
# Triangle Cron

Triangle Cron registers the Localzet Cron scheduler as a one-worker process in a Triangle Engine application. It reads task definitions from `config('cron')` and attaches them to the scheduler process when that server starts.

## Requirements

- PHP `^8.1`
- Triangle Engine `^9.0`
- Localzet Server `^7.1` (provided by Engine 9)
- Localzet Cron `^2.0`

Version 2.x targets Engine 9 and Server 7. Applications on Engine 8 and Server 4 must stay on Triangle Cron 1.x.

## Installation

```sh
composer require triangle/cron:^2.0
```

Add task definitions to `config/cron.php`:

```php
<?php

return [
[
'name' => 'cleanup-expired-records',
'rule' => '*/5 * * * *',
'callback' => static function (): void {
// Run a short, non-blocking task here.
},
],
];
```

Five-field rules use minute precision. Six-field rules can include seconds. Callbacks run on the Localzet Server event loop: keep them short and non-blocking, and send long-running work to a queue or another process.

## Runtime behavior

When Engine bootstraps a managed server startup (`start` or `restart`), the component registers a dedicated `Cron` server with one worker. At that worker's `onServerStart` event, it reads `config('cron', [])` and registers entries that have both a non-empty `rule` and a `callback`.

This is an in-process scheduler, not a durable job queue. Scheduled work is not persisted across restarts, and the component does not coordinate schedules across separate application installations. Keep the scheduler process to one worker unless the application deliberately wants each worker to execute every configured task.

## Checks

```sh
composer install
composer run check
```

The compatibility check verifies that the component implements Engine 9's autoload contract, creates its scheduler server through Server 7's startup helper, and loads only complete task definitions. CI runs the checks on PHP 8.1–8.5.

## License

AGPL-3.0-or-later.

Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
57 changes: 57 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Triangle Cron

Triangle Cron подключает планировщик Localzet Cron к приложению на Triangle Engine как отдельный процесс с одним worker. Компонент читает задания из `config('cron')` и регистрирует их при запуске этого процесса.

## Требования

- PHP `^8.1`
- Triangle Engine `^9.0`
- Localzet Server `^7.1` (устанавливается вместе с Engine 9)
- Localzet Cron `^2.0`

Версия 2.x предназначена для Engine 9 и Server 7. Приложения на Engine 8 и Server 4 должны оставаться на Triangle Cron 1.x.

## Установка

```sh
composer require triangle/cron:^2.0
```

Добавьте задания в `config/cron.php`:

```php
<?php

return [
[
'name' => 'cleanup-expired-records',
'rule' => '*/5 * * * *',
'callback' => static function (): void {
// Run a short, non-blocking task here.
},
],
];
```

Правила из пяти полей задают расписание с точностью до минуты. В правилах из шести полей можно указать секунды. Callback выполняется в event loop Localzet Server: он должен быть коротким и неблокирующим. Длительную работу передавайте в очередь или отдельный процесс.

## Работа во время запуска

При подготовке Engine к запуску сервера (`start` или `restart`) компонент регистрирует отдельный сервер `Cron` с одним worker. В обработчике `onServerStart` этого worker он читает `config('cron', [])` и регистрирует задания, в которых заданы непустые `rule` и `callback`.

Это планировщик в памяти процесса, а не надёжная очередь заданий. Расписание не сохраняется между перезапусками; компонент не согласует задания между отдельными установками приложения. Оставляйте один worker планировщика, если приложение специально не должно выполнять каждое задание на каждом worker.

## Проверки

```sh
composer install
composer run check
```

Проверка совместимости подтверждает контракт автозагрузки Engine 9, создание процесса планировщика через механизм запуска Server 7 и загрузку только полных описаний заданий. CI запускает проверки на PHP 8.1–8.5.

## Лицензия

AGPL-3.0-or-later.

Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
19 changes: 14 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
{
"name": "triangle/cron",
"description": "Triangle Cron Component",
"description": "Cron scheduler integration for Triangle Engine 9 and Localzet Server 7.",
"type": "library",
"keywords": [
"localzet",
"Triangle",
"Cron"
"Cron",
"scheduler",
"server"
],
"license": "AGPL-3.0-or-later",
"authors": [
Expand All @@ -28,9 +30,16 @@
},
"require": {
"php": "^8.1",
"triangle/engine": "^8.1",
"triangle/events": "^1.0",
"localzet/cron": "^1.0"
"triangle/engine": "^9.0",
"localzet/cron": "^2.0"
},
"scripts": {
"lint": "find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l",
"test": "php tests/compatibility.php",
"check": [
"@lint",
"@test"
]
},
"suggest": {
},
Expand Down
6 changes: 3 additions & 3 deletions src/Autoload.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<?php
/**
* @package Triangle Cron Component
* @link https://github.com/Triangle-org/Events
* @link https://github.com/Triangle-org/Cron
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down Expand Up @@ -44,4 +44,4 @@ public static function start(?string $arg = '', ?Server $server = null): void
};
}
}
}
}
6 changes: 3 additions & 3 deletions src/Config/cron.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

/**
* @package Triangle Cron Component
* @link https://github.com/Triangle-org/Events
* @link https://github.com/Triangle-org/Cron
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand All @@ -24,4 +24,4 @@
* For any questions, please contact <triangle@localzet.com>
*/

return [];
return [];
4 changes: 2 additions & 2 deletions src/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

/**
* @package Triangle Cron Component
* @link https://github.com/Triangle-org/Events
* @link https://github.com/Triangle-org/Cron
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
71 changes: 71 additions & 0 deletions tests/compatibility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php declare(strict_types=1);

/**
* @package Triangle Cron
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use Triangle\Cron\Autoload;
use Triangle\Engine\Config;
use Triangle\Engine\AutoloadInterface;
use localzet\Cron;
use localzet\Timer;

require dirname(__DIR__) . '/vendor/autoload.php';

if (!is_subclass_of(Autoload::class, AutoloadInterface::class)) {
throw new RuntimeException('Cron autoload must implement the Engine autoload contract.');
}

Autoload::start('application-command');

Config::set([
'cron' => [
[
'rule' => '*/5 * * * *',
'callback' => static function (): void {},
'name' => 'compatibility-check',
],
['rule' => '*/5 * * * *'],
],
]);
Timer::init();
Autoload::start('start');

$servers = \localzet\Server::getAllServers();
$server = end($servers);

if (!$server instanceof \localzet\Server || $server->name !== 'Cron') {
throw new RuntimeException('Cron must register a dedicated Server 7 process.');
}

if (!is_callable($server->onServerStart)) {
throw new RuntimeException('Cron must register its task loader on server startup.');
}

($server->onServerStart)($server);

if (count(Cron::getAll()) !== 1) {
throw new RuntimeException('Cron must register only complete task definitions.');
}

foreach (Cron::getAll() as $job) {
$job->destroy();
}

echo "OK: Engine 9 and Server 7 startup compatibility\n";