Conn2Flow
Docs navigation

Reference / Libraries

cron.php library

Scheduled routines: declaring a task in the module, scheduling the ticks on the server and what the gestor/cron.php engine actually runs.

Path in the Gestor bibliotecas/cron.php

Scheduled routines have three parts:

  1. The declaration, in the cron key of the module JSON, which the pipeline writes to the cron_tarefas table.

  2. The engine gestor/cron.php, a command-line script that runs the tasks of one frequency.

  3. The server scheduler (crontab, hosting panel), which calls the engine. Nothing in Conn2Flow creates this schedule: neither the installer nor the panel. Without it, no task runs.

The cron.php library holds what the engine, the resource compiler and the admin-cron panel share.

Declaring a task

At the root of <module>.json:

{
  "cron": [
    {
      "id": "trial-expiration",
      "nome": "Expire trial subscriptions",
      "funcao": "my_module_cron_expire_trials",
      "frequencia": "diario",
      "hora": "03:30",
      "parametros": { "days": 7 },
      "ativo": true
    }
  ]
}
Field
id Unique across all modules
funcao The PHP function. If it does not exist yet, the engine includes gestor/modulos/<module>/<module>.cron.php; <module>.php is never included
frequencia minutario, horario, diario (default), mensal or customizado
hora, dia HH:MM and day of month (1–31, mensal only), used to build expressao_cron
expressao_cron Five fields; required for customizado and overrides hora/dia
parametros Object passed to the function
ativo false stores the task paused

A task without id or funcao, with an unknown frequency or an invalid expression becomes an orphan at compile time and never reaches the database (resources). In the panel, ativo, expressao_cron and parametros can be changed and are preserved on deploy.

The task function

// gestor/modulos/my-module/my-module.cron.php
function my_module_cron_expire_trials($parametros) {
    $days = (int)($parametros['days'] ?? 7);
    // ...
    echo "12 subscriptions expired\n";           // becomes the run log
    return ['status' => 'aviso', 'log' => '3 without e-mail']; // optional
}

cron_tarefa_executar() captures everything the function prints and its return value:

  • ['status' => 'sucesso|erro|aviso', 'log' => …] sets the result;

  • false is an error; any other return is success;

  • an exception becomes an error and does not stop the other tasks.

The result goes to the task's own row in cron_tarefas (ultimo_disparo, ultima_duracao_ms, ultimo_status and ultimo_log, cut at 4000 bytes) and to gestor/logs/cron-<dd-mm-yyyy>.log.

Scheduling the engine

php gestor/cron.php frequencia=<frequency> [server=<domain>] [debug]
php gestor/cron.php tarefa=<id> [debug]      # one task, outside its window (a paused one does not run)
php gestor/cron.php listar

Register one tick per frequency in the server scheduler, with the library's default times (cron_expressao_padrao()):

*/10 * * * *  php /path/gestor/cron.php frequencia=minutario
0 * * * *     php /path/gestor/cron.php frequencia=horario
0 3 * * *     php /path/gestor/cron.php frequencia=diario
0 4 1 * *     php /path/gestor/cron.php frequencia=mensal

With a single folder with a .env in autenticacoes/, the domain is detected; with several, server=<domain> is required (without it, the engine exits with an error instead of running against the wrong database).

The admin-cron panel only infers whether there is a scheduler: whether any active task ran in the last 24 hours.

For compatibility, each tick also fires the cron.<frequency> hook (hooks).

Helper functions

  • cron_frequencias_validas(), cron_status_validos(): the vocabularies.

  • cron_expressao_valida($e): only the shape (five fields with digits and * , - /), not whether the values make sense.

  • cron_expressao_declarada($tarefa, $frequencia): the final expression, or null if invalid.

  • cron_tarefas_carregar($frequencia, $tarefaId, $todas, $campos): reads cron_tarefas (without deleted ones; without paused ones unless $todas).

Internal helpers (used by the functions above; rarely called directly): cron_callback_preparar(), cron_tarefa_registrar().

Functions

Generated from gestor/bibliotecas/cron.php · 9 functions

9 of 9

cron_expressao_padrao

view source · line 60 ↗
cron_expressao_padrao(string $frequencia): string|null

Expressão cron padrão de cada janela, usada quando a tarefa não declara uma.

Parameters

$frequenciastring

Returns

string|null
null para 'customizado', que não tem forma derivável.

cron_expressao_declarada

view source · line 85 ↗
cron_expressao_declarada(array $tarefa, string $frequencia): string|null

Resolve a expressão cron de 5 campos de uma tarefa declarada.

Parameters

$tarefaarray
$frequenciastring

Returns

string|null
null quando a declaração é inválida.

cron_callback_preparar

view source · line 126 ↗
cron_callback_preparar(array $tarefa): string|null

Garante que o callback declarado exista antes de invocá-lo.

Parameters

$tarefaarray
Linha de cron_tarefas.

Returns

string|null
Mensagem de erro, ou null quando o callback está disponível.

cron_tarefa_executar

view source · line 164 ↗
cron_tarefa_executar(array $tarefa): array{status: string, duracao: int, log: string}

Executa uma tarefa e devolve o resultado normalizado.

Parameters

$tarefaarray
Linha de cron_tarefas.

Returns

array{status: string, duracao: int, log: string}

cron_tarefa_registrar

view source · line 232 ↗
cron_tarefa_registrar(string $id, string $status, int $duracaoMs, string $log): void

Persiste o resultado da execução na própria linha da tarefa.

Parameters

$idstring
$statusstring
$duracaoMsint
$logstring

Returns

void

cron_tarefas_carregar

view source · line 255 ↗
cron_tarefas_carregar(string|null $frequencia = null, string|null $tarefaId = null, bool $todas = false, array $campos = null): array

Carrega as tarefas elegíveis do banco.

Parameters

$frequenciastring|null
Janela do tick; null quando o alvo é uma tarefa específica.
$tarefaIdstring|null
Disparo avulso, que ignora a janela mas não o estado ativo.
$todasbool
Listagem administrativa: traz inclusive as pausadas.
$camposarray
Colunas desejadas; o padrão cobre o despacho.

Returns

array

The Future is Hybrid: Human + AI.

Conn2Flow is the tool. If you need the Architect to design your company's strategy using this technology...

Hire Specialized Consulting