Many features need work that no user starts with a click. Some examples:
Admidio has no scheduler of its own. Instead, core, modules and plugins register such periodic and maintenance tasks with Admidio, and Admidio runs them in two ways:
A well-written task supports both ways. It decides for itself whether something is due, and it does the work exactly once, whichever of the two ways gets there first. An installation with cron then gets punctual execution, and an installation without cron still works, just later: as soon as somebody visits the site.
For administrator documentation see Using the Admidio CLI and the CLI command reference.
This section is for both core developers and plugin developers. The details follow in the later sections.
| Part | Purpose | Required |
|---|---|---|
A service method runIfDue() | Decides whether work is due, claims it in the database and does it. All the logic lives here. | yes |
| A maintenance job | Lets the scheduled admidio maintenance:run call runIfDue(). | yes |
A listener on the action request_finished | Lets Admidio call runIfDue() after a page request. Needed if the task has to work without cron, or should react quickly. | recommended |
A command of your own (e.g. example:sync) | Lets an administrator run the task by hand, with options such as --dry-run, for support and testing. | optional |
| Core and core modules | Plugins | |
|---|---|---|
| Maintenance job | CliTaskRegistry::registerCoreMaintenanceJob() in CoreTasks::registerMaintenanceJobs(). Core modules may use CliTaskRegistry::registerMaintenanceJob() in modules/<module>/cli.php. | CliTaskRegistry::registerMaintenanceJob() in plugins/<plugin>/cli.php |
| Request listener | Hooks::addAction('request_finished', …) during the bootstrap of the request | Hooks::addAction('request_finished', …) in the plugin's entry file (plugin.php) |
| Own command | CoreTasks or modules/<module>/cli.php | CliTaskRegistry::register() in plugins/<plugin>/cli.php |
Names of jobs and commands of a module or plugin use its own namespace, i.e. the directory name: example:cleanup for plugins/example. Core jobs have plain names (sessions, memberships).
The service holds the logic. It is called the same way from cron and from a request:
<?php namespace AdmidioPlugin\Example\Service; class CleanupService { /** * Remove the expired entries of the current organization, at most once per hour. * @return int|null Number of removed entries, or null if nothing was due. */ public static function runIfDue(): ?int { // 1. cheap check: is anything due? (e.g. a preference with the time of the last run) // 2. claim the run atomically in the database, so that a parallel request or cron run // does not do the same work again; return null if somebody else claimed it // 3. do the work for $gCurrentOrgId, within a time budget return $removed; } }
plugins/example/cli.php registers the maintenance job, and optionally a command:
<?php use Admidio\Infrastructure\Cli\CliTaskRegistry; use AdmidioPlugin\Example\Service\CleanupService; if (PHP_SAPI !== 'cli') { exit('This page may not be called directly!'); } CliTaskRegistry::registerMaintenanceJob( 'example:cleanup', static function (): string { $removed = CleanupService::runIfDue(); return $removed === null ? 'nothing due' : $removed . ' entries removed'; }, 'Remove expired example entries.' );
plugins/example/plugin.php takes part in the request route:
use Admidio\Hooks\Hooks; use AdmidioPlugin\Example\Service\CleanupService; Hooks::addAction('request_finished', static function (): void { CleanupService::runIfDue(); }, 50, null, 'example-cleanup');
That is all. Once the plugin is enabled:
admidio maintenance:jobs lists example:cleanup;
Plugins that also support Admidio 6.0 Beta 1, which has neither the job registry nor request_finished, guard the registration, so that cli.php still loads there. Hooks::addAction() for an action that is never dispatched is harmless, so it needs no guard:
if (method_exists(CliTaskRegistry::class, 'registerMaintenanceJob')) { CliTaskRegistry::registerMaintenanceJob(/* ... */); }
The provisioning plugin is a real-world example of the whole pattern:
cli.php registers the job provisioning:sync and the command of the same name;Service/RequestRunner listens on request_finished with a configurable time budget;Service/Scheduler decides what is due.admidio maintenance:run --yes --as=cron-admin
|
+-- CLI bootstrap (system/bootstrap/cli.php): database, organization, settings, language
| no PHP session, no adm_sessions row, no navigation, $gValidLogin = false
|
+-- access policy (adm_my_files/cli-config.php) and acting user (--as)
|
+-- core registers its jobs, then modules/*/cli.php and the cli.php of every enabled plugin
|
+-- for each registered job (core first, then modules and plugins, in registration order):
| call the job's callback
| returns -> row job | success | returned string (if any)
| throws -> row job | failed | exception message (the next job still runs)
|
+-- print all rows (--format), exit
|
+-- request_finished listeners run at the end of the process as well (see below)
The relevant classes:
Admidio\Infrastructure\Cli\CliTaskRegistry registerCoreMaintenanceJob(), registerMaintenanceJob(), getMaintenanceJobs() Admidio\Infrastructure\Cli\CoreTasks registers the core jobs; the commands maintenance:run and maintenance:jobs Admidio\Infrastructure\Utils\Maintenance repair operations on the database (categories, document paths)
The Maintenance class contains only repairs and reorganisation of existing data. Every other job calls the service of the area it belongs to.
At the end of every request, system/bootstrap/shutdown.php dispatches the action request_finished, if any listener is registered:
fastcgi_finish_request(). The browser already has the complete page and the visitor does not wait for the listeners. Without PHP-FPM (e.g. mod_php), the listeners run before the connection closes and the visitor does wait. Keep a time budget for this reason.Hooks::doActionCatchErrors(). A failing listener is logged and does not affect the response or the other listeners.maintenance:run. A task whose job just ran should not start a second time in the same process. runIfDue() normally sees that nothing is due any more. Otherwise set a static flag in the job callback, as the provisioning plugin does with RequestRunner::skip().
Two core tasks predate this action and are called directly from system/common.php:
MembershipPeriodService::runIfDueSilently()), on the first request of the day, before the page is rendered.
New code should use request_finished.
| Job | Implementation | Scope | Standalone command | Request route |
|---|---|---|---|---|
categories | Maintenance::reorganizeCategories() | all organizations | maintenance:repair-categories | no |
documents | Maintenance::repairDocumentsFilesPath() | all organizations | maintenance:repair-documents | no |
sessions | deletes adm_sessions rows inactive for more than 30 minutes | global | session:cleanup | every request (Session::tableCleanup()) |
auto-logins | AutoLogin::tableCleanup() | global | autologin:cleanup | whenever a new auto-login is saved |
sso-tokens | deletes expired, revoked and used OIDC tokens and authorization codes | global | sso:token-cleanup | no |
saml-metadata | SAMLMetadataRefreshService::refreshDue() | global | sso:saml-metadata-refresh | no |
update-check | reads the public release information for the update notice of the administrators | organization | update:check | at most every 12 hours, on a request of an administrator (PreferencesService::checkForUpdateIfDue()) |
memberships | MembershipPeriodService::runIfDue(): memberships whose start or end date was reached; dispatches membership_period_changed | organization | — | first request of the day |
admidio maintenance:jobs lists all registered jobs of an installation, including those of modules and plugins.
The jobs without a request route are tidiness only: nothing breaks if they never run. A task whose result matters to users must have a request route.
admidio maintenance:run [--job=JOB]... [--yes] [--format=table|json|json-api|csv|md|dokuwiki] admidio maintenance:jobs [--format=...]
--job, every registered job runs. --job can be repeated. An unknown name is rejected with the list of known jobs.maintenance:run changes data, so it asks for confirmation. A scheduler passes --yes. --yes cannot be set as a default in cli-config.php, by design.--as). It must be allowed to administrate the component CORE, i.e. an administrator. $gCliAllowedActors in cli-config.php can restrict which Admidio accounts a cron account may act as.config.php, or the one given with --organization. Global jobs ignore it. Multi-organization installations need one scheduler entry per organization. The global jobs then run several times, which is harmless because they are idempotent.Exit codes:
| Code | Constant | Meaning |
|---|---|---|
| 0 | CliApplication::EXIT_SUCCESS | every requested job succeeded |
| 6 | CliApplication::EXIT_FAILED | at least one job failed; the others still ran (see the status column) |
| 2 | CliApplication::EXIT_USAGE | invalid options |
| 5 | CliApplication::EXIT_REJECTED | refused by the access policy or missing rights |
A scheduler entry runs hourly; every job decides for itself whether it has work:
5 * * * * /usr/bin/php /var/www/admidio/admidio maintenance:run --yes --as=cron-admin --no-interaction --format=json >> /var/log/admidio-maintenance.log 2>&1
The command line must be enabled in adm_my_files/cli-config.php. A minimal policy for a dedicated cron account:
$gCliEnabled = true; $gCliAllowedUsers = 'www-data'; $gCliAllowedCommands = 'maintenance:run'; $gCliAllowedActors = 'cron-admin';
message column, or nothing.failed and maintenance:run exits with 6. A problem with a single item (one recipient, one client) is logged with $gLogger and counted in the summary. It must not fail the job or stop the remaining items.maintenance:run.Idempotent. A task may run every few minutes or once a week, twice in a row, from cron and from a request at the same moment. Running it again must not repeat work.
State in the database. Keep “already done” in the database, e.g. as a preference with the date of the last run or as a row per processed item. Do not keep it in files below adm_my_files. That way it survives a move of the installation, works with several web servers and is part of the backup.
Claim before acting. Claim the work with an atomic statement before doing it. Two examples:
UPDATE … WHERE prf_value = <old value> that only one process wins, as in MembershipPeriodService::claim();INSERT into a table with a unique index.For work with side effects (mails, calls to other systems), release the claim if the action fails. If you act first and record afterwards, a crash in between repeats the action. Lock files are not needed.
Windows, not exact dates. Ask “what is due and not done yet”, never “what is due today”. A task that only acts when DATE_NOW equals a calculated day loses that work whenever nothing ran on that day, and also when the triggering data changed later (e.g. an event created inside its reminder period). MembershipPeriodService catches up from the last processed day to today.
Bounded runtime. On the request route, the visitor may be waiting, and PHP's time limits apply. Process a limited number of items or stop starting new items after a time budget. The rest is due next time. Examples: SAMLMetadataRefreshService::refreshDue($maxClients = 20, $timeBudget = 45), and the request budget setting of the provisioning plugin.
Organization scope. Decide whether the task is global (sessions, tokens) or belongs to an organization. It belongs to an organization if it reads $gSettingsManager, sends mails in the organization's name, or uses entities whose readData() checks $gCurrentOrgId, such as Event. Restrict such a task's queries to $gCurrentOrgId. Entities of another organization throw SYS_NO_RIGHTS.
No web context. In both routes there is no reliable session: on the command line, $gValidLogin is false and $gCurrentUser is the --as account. On the request route, the task runs for whoever happened to visit. Never make a task depend on the rights of the current user. Do not include system/common.php from scripts and do not fake $_SERVER. For the URL of the installation use ADMIDIO_URL.
Repairs go to Maintenance, everything else to its module. Only operations that repair or reorganise existing data belong in Admidio\Infrastructure\Utils\Maintenance.
Off by default when it affects users. A task that sends mails or changes visible data must not start doing so for existing data just because an installation was updated. Make it opt-in through a preference.
English for the CLI, translations for users. CLI output is not localized yet. Job summaries are English. Text that reaches users, such as mails, goes through $gL10n as usual.
php admidio maintenance:run --job=example:cleanup --yes --as=admin --format=json
runIfDue() directly (see tests/Integration). Also test the situations that occur in practice:Hooks::doAction('request_finished') (see tests/Integration/Core/RequestFinishedTest.php).runIfDue()). It is not in CoreTasks, and it is not in Maintenance unless it is a repair.registerCoreMaintenanceJob() for core, registerMaintenanceJob() in cli.php for modules and plugins. Its callback returns a summary and throws only when the job as a whole failed.request_finished listener is registered if the task has to work without cron.--dry-run.