cron_example.module
1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/**
* @file
* Demonstrates use of the Cron API in Drupal - hook_cron().
*/
/**
* @defgroup cron_example Example: Cron
* @ingroup examples
* @{
* Example using Cron API, including hook_cron() and @QueueWorker plugins
*
* This example is part of the Examples for Developers Project
* which you can download and experiment with at
* http://drupal.org/project/examples
*/
/**
* Implements hook_cron().
*
* We implement hook_cron() to do "background" processing. It gets called every
* time the Drupal cron runs. We then decide what has to happen in response.
*
* In this example, we log a message after the time given in its config
* variable 'next_execution'. Then we update that variable to a time in the
* future.
*/
function cron_example_cron() {
// We access our configuration.
$cron_config = \Drupal::configFactory()->getEditable('examples.cron');
// Default to an hourly interval. Of course, cron has to be running at least
// hourly for this to work.
$interval = $cron_config->get('interval');
$interval = !empty($interval) ? $interval : 3600;
// We usually don't want to act every time cron runs (which could be every
// minute) so keep a time for the next run in a variable.
$next_execution = $cron_config->get('next_execution');
$next_execution = !empty($next_execution) ? $next_execution : 0;
if (REQUEST_TIME >= $next_execution) {
// This is a silly example of a cron job.
// It just makes it obvious that the job has run without
// making any changes to your database.
\Drupal::logger('cron_example')->notice('cron_example ran');
if (\Drupal::state()->get('cron_example_show_status_message')) {
drupal_set_message(t('cron_example executed at %time', ['%time' => date_iso8601(REQUEST_TIME)]));
\Drupal::state()->set('cron_example_show_status_message', FALSE);
}
$cron_config->set('next_execution', REQUEST_TIME + $interval)->save();
}
}
/**
* @} End of "defgroup cron_example".
*/