Drupalwoo ☉

How To Use Drupal’s Cron API For Scheduled Cleanup Tasks

Routine cleanup keeps a Drupal website responsive, easier to maintain and less expensive to operate. Temporary files, expired records, abandoned sessions, stale queue items and old log entries can accumulate quietly until database queries slow down or disk space becomes scarce. Drupal’s Cron API provides a consistent way to run this maintenance without asking an administrator to perform it manually.

The most reliable approach combines a small cron hook with Drupal’s State API, Queue API, database services and logging system. The right design depends on the amount of data, how long the task takes and how much risk is involved if a run stops halfway through.

Australian websites have a few practical considerations as well. A site hosted in Sydney may use Australian Eastern Standard Time, while a cloud server may use UTC. Daylight saving in New South Wales, Victoria, Tasmania and the Australian Capital Territory can affect assumptions about execution times. Sites handling local customer data should also retain only the records required for business, privacy and audit obligations.

Understanding Drupal Cron

Drupal cron is a scheduled maintenance process that invokes registered cron handlers. Core uses it for tasks such as clearing caches, processing queues, updating search indexes and removing expired data. Custom modules can participate by implementing a hook_cron() function in the module’s .module file.

Cron does not automatically mean that a task runs at an exact minute. Drupal’s automated cron mechanism is triggered by site traffic, so a quiet community website may run maintenance later than expected. For predictable processing, configure the server’s system cron, a hosting control panel scheduler or a platform task to execute Drush:

*/15 * * * * cd /var/www/html && vendor/bin/drush cron

The command above runs every 15 minutes. Adjust the path and frequency for the deployment environment. A busy Melbourne retail site may have enough traffic for automated cron, while a low-traffic intranet or campaign microsite will usually benefit from a server-level schedule.

Drupal’s cron API is intended for short, repeatable work. It is not a replacement for a long-running worker process. If a cleanup operation could process thousands of entities, divide it into smaller batches or place work on a queue.

Choosing What To Clean

Start by defining the data lifecycle. A cleanup task should answer what qualifies as stale, how long records must be retained and whether a user or administrator needs to restore them. For example, temporary import rows might expire after 24 hours, abandoned checkout data after seven days and application logs after 30 days.

Use Drupal’s own services where possible. The State API is suitable for storing a timestamp or a small operational flag, while the Key-Value API can hold lightweight values. Content entities should generally be removed through entity storage so field data, revisions and related hooks are handled correctly. Direct SQL is appropriate for custom tables when the schema and deletion rules are fully controlled by the module.

A useful design separates selection from deletion. First identify a limited set of eligible records, then process that set and record the result. This makes the task easier to test and reduces the chance of a single malformed row stopping all cleanup. It also gives site owners clearer reporting when a deletion policy changes.

For broader thinking about maintainable web systems and practical development workflows, these Drupal development notes provide useful context alongside Drupal’s own documentation.

Writing A Basic Cron Handler

A simple module can register a cleanup operation with hook_cron(). The example below deletes old records from a custom table in small batches. The table name, columns and retention period must match the module’s schema.

/**
 * Implements hook_cron().
 */
function example_cleanup_cron(): void {
  $database = \Drupal::database();
  $cutoff = \Drupal::time()->getRequestTime() - (30 * 24 * 60 * 60);

  $ids = $database->select('example_temp_data', 't')
    ->fields('t', ['id'])
    ->condition('created', $cutoff, '<')
    ->range(0, 100)
    ->execute()
    ->fetchCol();

  if (!$ids) {
    return;
  }

  $database->delete('example_temp_data')
    ->condition('id', $ids, 'IN')
    ->execute();

  \Drupal::logger('example_cleanup')->notice(
    'Removed @count expired temporary records.',
    ['@count' => count($ids)]
  );
}

The batch size of 100 limits database work during a single cron request. Because the query always selects records older than the cutoff, later runs can continue where the previous run stopped. This pattern is safer than loading every matching row into memory.

Avoid performing expensive service lookups or network requests inside the handler. Dependency injection is preferable in a custom service, while the procedural hook can call Drupal services for a small implementation. If the task must run less frequently than the overall cron interval, store the last execution time in State API and return early until the required interval has passed.

For entity cleanup, inject the relevant storage handler and use an entity query with an explicit access setting for administrative maintenance. Delete entities in modest batches and consider revisions, translations and references before removing them. A content entity may have related data that a direct database delete would leave behind.

Scaling Work With The Queue API

The Queue API is a better fit when cleanup involves many independent items. The cron hook can discover eligible IDs and add them to a queue, while a queue worker processes one item at a time. This keeps the cron callback short and allows Drupal to retry items that fail.

A queue worker is defined as a plugin. In a traditional annotation-based module, its structure resembles this:

/**
 * @QueueWorker(
 *   id = "example_cleanup",
 *   title = @Translation("Example cleanup"),
 *   cron = {"time" = 30}
 * )
 */
class ExampleCleanupWorker extends QueueWorkerBase {

  public function processItem($data): void {
    $storage = \Drupal::entityTypeManager()
      ->getStorage('example_record');

    if ($record = $storage->load($data['id'])) {
      $record->delete();
    }
  }

}

The worker’s cron setting gives Drupal a processing time budget rather than a promise that every item will be completed in one request. The enqueueing code should avoid adding duplicate items, perhaps by using a state marker or a custom status column. A queue item should contain the smallest useful payload, commonly an entity ID and perhaps a cleanup reason.

Queue processing needs failure handling. A worker should tolerate an item that has already been deleted, and external operations should be idempotent so that a retry does not create a second side effect. If the task is business-critical or the queue becomes large, monitor it separately rather than assuming a successful drush cron means every item was processed.

Preventing Duplicate And Unsafe Runs

Cron can overlap when a server starts another process before the previous one finishes. Use Drupal’s Lock service when the cleanup must have only one active execution. Acquire a named lock before selecting records, and release it in a finally block so an exception does not leave the lock held longer than necessary.

$lock = \Drupal::lock();
if (!$lock->acquire('example_cleanup', 300)) {
  return;
}

try {
  // Select and process a small batch.
}
finally {
  $lock->release('example_cleanup');
}

The lock timeout should exceed the expected batch duration but remain finite. A lock is not a substitute for transactions. When several related database changes must succeed together, use a transaction and keep its scope small to avoid holding database locks for too long.

Make deletion conditions conservative. Compare timestamps in a consistent timezone, use parameterised queries and never build SQL by concatenating user input. Check whether an item is still eligible immediately before deletion if another process can update it. For personal information, document the retention period and ensure cleanup aligns with the organisation’s privacy policy and Australian obligations.

Log useful operational details without exposing sensitive values. A message containing the number of deleted records, duration and batch identifier is generally more useful than logging email addresses or full payloads. On a production site, review log retention as well: keeping every cleanup message forever can create the same storage problem the task was meant to solve.

Running And Monitoring Cron Reliably

The Status report at /admin/reports/status can reveal whether cron has run recently. Administrators can also run drush cron -v during testing and inspect the recent watchdog messages. Test first on a staging copy with realistic data, then deploy the module and schedule the task in production.

For a managed Australian host, ask whether scheduled jobs use the server’s local timezone or UTC. A job configured for 2:00 am may run during peak Australian traffic after a daylight-saving change if the server is in a different region. Scheduling by UTC and documenting the equivalent local time is often clearer for teams working across Brisbane, Sydney and Perth.

Monitor more than the exit code. A cron command can complete successfully while a particular queue worker repeatedly fails. Track queue depth, the age of the oldest pending item, the number of deleted records and the duration of each batch. An alert is useful when no cleanup has completed within a reasonable window or when the queue grows continuously.

Use the hosting environment’s process limits as part of the design. Shared hosting may impose short execution limits, while a container platform may terminate a job at a fixed timeout. Small batches, indexed columns and resumable processing allow the cleanup to make progress within those constraints.

Selecting The Right Scheduling Pattern

The scheduling method should match the data volume and operational importance of the task. A direct cron hook is simple for a few rows and can be easy to maintain in a small custom module. A queue worker adds structure and resilience when each record can be processed independently. A Drush command or external job is preferable when the operation needs a long runtime, special deployment permissions or detailed reporting outside the web request.

Cleanup pattern Suitable use Main benefit Main caution
Direct hook_cron() batch Small custom-table cleanup Minimal code and easy deployment Must remain fast and bounded
Cron hook with State API Hourly or daily maintenance Prevents work on every cron run State must be updated carefully
Queue API worker Large sets of independent records Resumable processing and retries Requires queue monitoring
Drush command Long or administrative jobs Better control over runtime and output Needs reliable server scheduling
Database retention policy High-volume technical data Efficient removal close to storage Must match application and backup rules

For a small Drupal site in Adelaide, a 15-minute Drush schedule with a 100-row batch may be sufficient. A national commerce platform with large order, import or log volumes will usually need indexed queries, queues, external monitoring and a documented retention policy. The same PHP code should not be copied between those environments without reviewing scale and failure behaviour.

Practical Recommendations For Production

Before enabling deletion in production, confirm the schema, backup policy and expected record counts. Run the selection query without deleting anything, review the matches and measure execution time. Add indexes to columns used for date filtering or status checks, particularly when the table has grown over several years.

Keep the task observable and reversible where the business requires it. A soft-delete status, export archive or delayed purge can provide a recovery period, although it also creates additional storage and policy responsibilities. Once the task is stable, document its schedule, retention rule, owner and expected log messages in the project repository.

A well-designed Drupal cron cleanup task should be predictable, resumable and quiet when there is nothing to do. By combining the Cron API with batching, locks, queues and clear monitoring, site administrators can keep routine maintenance away from manual workflows while preserving control over data and server resources.