Inhaltsverzeichnis

Periodic and maintenance tasks (Admidio 6)

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:

  1. With the scheduled maintenance run. The administrator sets up one scheduled job (cron, systemd timer, Windows Task Scheduler) that calls the Admidio command line. This runs every registered task, reliably and on time, whether or not anybody uses the website.
  2. Automatically, at the end of normal page requests. After a page has been sent to the browser, Admidio gives tasks the chance to do work that is due. This keeps installations working that have no cron and no PHP command line, which is common on shared hosting. It also lets changes take effect within seconds of the request that caused them.

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.

Overview: scheduling work in your code

This section is for both core developers and plugin developers. The details follow in the later sections.

What you write

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

Where you register it

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).

A complete plugin example

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:

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:

How the two ways work

The scheduled maintenance run

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.

The request route: the action request_finished

At the end of every request, system/bootstrap/shutdown.php dispatches the action request_finished, if any listener is registered:

Two core tasks predate this action and are called directly from system/common.php:

New code should use request_finished.

The core jobs

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.

Running the maintenance jobs

admidio maintenance:run [--job=JOB]... [--yes] [--format=table|json|json-api|csv|md|dokuwiki]
admidio maintenance:jobs [--format=...]

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';

Writing a maintenance job

The job callback

Guidelines

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:

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.

Testing

Checklist

  1. The logic is in a service method of its module (runIfDue()). It is not in CoreTasks, and it is not in Maintenance unless it is a repair.
  2. The task is idempotent, keeps its state in the database and claims work before doing it.
  3. It asks “due and not done”, not “due today”.
  4. The runtime of one run is bounded.
  5. The organization scope is decided and respected.
  6. It is off by default if it affects users, and a preference controls it.
  7. A maintenance job is registered: 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.
  8. A request_finished listener is registered if the task has to work without cron.
  9. If useful, there is a command of its own, with --dry-run.
  10. Tests cover: a repeated run, a missed run, another organization, a failing item.
  11. For core jobs, the table on this page and the administrator documentation are updated.