Cron API
Cron permette di eseguire periodicamente operazioni di manutenzione, ad esempio:
- eliminare dati scaduti
- aggiornare indici
- recuperare dati da servizi esterni
- controllare lo stato di risorse
- creare elementi in una queue
- inviare notifiche
- aggiornare informazioni calcolate
Per intercettare l'esecuzione di cron si usa hook_cron().
La frequenza dell'esecuzione di cron non è predeterminata ma dipende dalle operazioni che compie, per sapere quando una certa esecuzione di cron è iniziata si usa:
$this->time->getRequestTime();
Queue API
La Queue API permette di memorizzare attività che devono essere elaborate successivamente:
$queue = $this->queueFactory->get(
'nome_modulo_forecast_refresh',
);
$queue->createItem([
'requested_at' => $requestTime,
]);
// il consumer mantiene il possesso dell'item per 30 secondi
$item = $queue->claimItem(30);
QueueWorker
Il QueueWorker è un plugin, non va aggiunto al file .services.yml.
Nel file src/Plugin/QueueWorker/ ForecastRefreshQueueWorker.php:
<?php
declare(strict_types=1);
namespace Drupal\nome_modulo\Plugin\QueueWorker;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\Attribute\QueueWorker;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\nome_modulo\Service\ForecastClientInterface;
use Drupal\nome_modulo\ForecastStatusStorage;
use SuspendQueueException;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Refreshes the cached weather forecast.
*/
#[QueueWorker(
id: 'nome_modulo_forecast_refresh',
title: new TranslatableMarkup(
'Refresh weather forecast',
),
cron: [
'time' => 30, // indica quanto tempo Drupal cron può dedicare all'elaborazione di questaa queue durante una cron run
],
)]
final class ForecastRefreshQueueWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface
{
/**
* Constructs a ForecastRefreshQueueWorker object.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly ForecastClientInterface $forecastClient,
private readonly ForecastStatusStorage $forecastStatusStorage,
private readonly CacheTagsInvalidatorInterface $cacheTagsInvalidator,
private readonly TimeInterface $time,
)
{
parent::__construct(
$configuration,
$plugin_id,
$plugin_definition,
);
}
/**
* {@inheritdoc}
*/
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition,
): static
{
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get(
ForecastClientInterface::class,
),
$container->get(
'nome_modulo.forecast_status_storage',
),
$container->get(
'cache_tags.invalidator',
),
$container->get(
'datetime.time',
),
);
}
/**
* {@inheritdoc}
*/
public function processItem(
mixed $data,
): void
{
$this->cacheTagsInvalidator // prima invalidiamo il dato corrente
->invalidateTags([
'nome_modulo:forecast',
]);
$forecast = //poi prendiamo il dato aggiornato
$this->forecastClient
->getForecast();
if ($forecast === NULL) {
throw new SuspendQueueException(
'The weather forecast could not be refreshed.',
);
}
$this->forecastStatusStorage
->setLastSuccessfulRefresh(
$this->time->getCurrentTime(),
);
}
}
?>
Batch API
La Batch API viene utilizzata per operazioni lunghe avviate dall'utente che devono essere suddivise in più passaggi per evitare timeout o memory limit, ad esempio importare un gran numero di record, aggiornare un numero elevato di nodi ecc....
Metodi disponibili:
- setTitle()
- setInitMessage()
- setProgressMessage()
- setErrorMessage()
- setFinishCallback()
- addOperation()
- toArray()
Time API
Metodi principali:
- getRequestTime() momento in cui inizia la richiesta
- getCurrentTime() momento effettivo della chiamata
- getRequestMicroTime()
- getCurrentMicroTime()
Lock API
Metodi principali:
- acquire()
- lockMayBeAvailable()
- wait()
- release()
- releaseAll()
Messenger API
Messenger API permette di mostrare messaggi runtime all'utente corrente:
$this->messenger->addStatus(
$this->t(
'The operation completed successfully.',
),
);