cron_example.module

Tracking 8.x-1.x branch
  1. drupal
    1. 7 contributions/examples/cron_example/cron_example.module
    2. 8 contributions/examples/cron_example/cron_example.module

Demonstrates use of the Cron API in Drupal - hook_cron()

Functions & methods

NameDescription
cron_example_add_jobs_to_queue#submit function used to add the items to the queue when signaled by the form.
cron_example_cronImplements hook_cron().
cron_example_cron_queue_infoImplements hook_cron_queue_info().
cron_example_formThe form to provide a link to cron.php.
cron_example_form_cron_run_submitAllow user to directly execute cron, optionally forcing it.
cron_example_menuImplements hook_menu().
cron_example_queue_1_workerSimple workers for the two queues.
cron_example_queue_2_worker
cron_example_queue_report_workSimple reporter for the workers.

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * Demonstrates use of the Cron API in Drupal - hook_cron()
  5. */
  6. /**
  7. * @defgroup cron_example Example: Cron
  8. * @ingroup examples
  9. * @{
  10. * Example using Cron API, including hook_cron() and hook_cron_queue_info().
  11. *
  12. * This example is part of the Examples for Developers Project
  13. * which you can download and experiment with at
  14. * http://drupal.org/project/examples
  15. */
  16. /**
  17. * Implements hook_menu().
  18. */
  19. function cron_example_menu() {
  20. $items['examples/cron_example'] = array(
  21. 'title' => 'Cron Example',
  22. 'page callback' => 'drupal_get_form',
  23. 'page arguments' => array('cron_example_form'),
  24. 'access callback' => TRUE,
  25. );
  26. return $items;
  27. }
  28. /**
  29. * The form to provide a link to cron.php.
  30. */
  31. function cron_example_form($form, &$form_state) {
  32. $form['status'] = array(
  33. '#type' => 'fieldset',
  34. '#title' => t('Cron status information'),
  35. );
  36. $form['status']['intro'] = array(
  37. '#markup' => '<div>' . t('The cron example demonstrates hook_cron() and hook_cron_queue_info() processing. If you have administrative privileges you can run cron from this page and see the results.') . '</div>',
  38. );
  39. $form['status']['last'] = array(
  40. '#markup' => '<div>' . t('cron_example_cron() will next execute the first time cron runs after %time (%seconds seconds from now)' . '</div>',
  41. array(
  42. '%time' => date_iso8601(variable_get('cron_example_next_execution', time())),
  43. '%seconds' => variable_get('cron_example_next_execution', time()) - time(),
  44. )
  45. ),
  46. );
  47. if (user_access('administer site configuration')) {
  48. $form['cron_run'] = array(
  49. '#type' => 'fieldset',
  50. '#title' => t('Run cron manually'),
  51. );
  52. $form['cron_run']['cron_reset'] = array(
  53. '#type' => 'checkbox',
  54. '#title' => t("Run cron_example's cron regardless of whether interval has expired."),
  55. '#default_value' => FALSE,
  56. );
  57. $form['cron_run']['cron_trigger'] = array(
  58. '#type' => 'submit',
  59. '#value' => t('Run cron now'),
  60. '#submit' => array('cron_example_form_cron_run_submit'),
  61. );
  62. }
  63. $form['cron_queue_setup'] = array(
  64. '#type' => 'fieldset',
  65. '#title' => t('Cron queue setup (for hook_cron_queue_info(), etc.)'),
  66. );
  67. $queue_1 = DrupalQueue::get('cron_example_queue_1');
  68. $queue_2 = DrupalQueue::get('cron_example_queue_2');
  69. $form['cron_queue_setup']['current_cron_queue_status'] = array(
  70. '#markup' => '<div>' . t('There are currently %queue_1 items in queue 1 and %queue_2 items in queue 2',
  71. array(
  72. '%queue_1' => $queue_1->numberOfItems(),
  73. '%queue_2' => $queue_2->numberOfItems(),
  74. )) . '</div>',
  75. );
  76. $form['cron_queue_setup']['num_items'] = array(
  77. '#type' => 'select',
  78. '#title' => t('Number of items to add to queue'),
  79. '#options' => drupal_map_assoc(array(1, 5, 10, 100, 1000)),
  80. '#default_value' => 5,
  81. );
  82. $form['cron_queue_setup']['queue'] = array(
  83. '#type' => 'radios',
  84. '#title' => t('Queue to add items to'),
  85. '#options' => array(
  86. 'cron_example_queue_1' => t('Queue 1'),
  87. 'cron_example_queue_2' => t('Queue 2'),
  88. ),
  89. '#default_value' => 'cron_example_queue_1',
  90. );
  91. $form['cron_queue_setup']['submit'] = array(
  92. '#type' => 'submit',
  93. '#value' => t('Add jobs to queue'),
  94. '#submit' => array('cron_example_add_jobs_to_queue'),
  95. );
  96. $form['configuration'] = array(
  97. '#type' => 'fieldset',
  98. '#title' => t('Configuration of cron_example_cron()'),
  99. );
  100. $form['configuration']['cron_example_interval'] = array(
  101. '#type' => 'select',
  102. '#title' => t('Cron interval'),
  103. '#description' => t('Time after which cron_example_cron will respond to a processing request.'),
  104. '#default_value' => variable_get('cron_example_interval', 60*60),
  105. '#options' => array(
  106. 60 => t('1 minute'),
  107. 300 => t('5 minutes'),
  108. 3600 => t('1 hour'),
  109. 60*60*24 => t('1 day'),
  110. ),
  111. );
  112. return system_settings_form($form);
  113. }
  114. /**
  115. * Allow user to directly execute cron, optionally forcing it.
  116. */
  117. function cron_example_form_cron_run_submit($form, &$form_state) {
  118. if (!empty($form_state['values']['cron_reset'])) {
  119. variable_set('cron_example_next_execution', 0);
  120. }
  121. // We don't usually use globals in this way. This is used here only to
  122. // make it easy to tell if cron was run by this form.
  123. $GLOBALS['cron_example_show_status_message'] = TRUE;
  124. if (drupal_cron_run()) {
  125. drupal_set_message(t('Cron ran successfully.'));
  126. }
  127. else {
  128. drupal_set_message(t('Cron run failed.'), 'error');
  129. }
  130. }
  131. /**
  132. * #submit function used to add the items to the queue when signaled by
  133. * the form.
  134. */
  135. function cron_example_add_jobs_to_queue($form, &$form_state) {
  136. $queue = $form_state['values']['queue'];
  137. $num_items = $form_state['values']['num_items'];
  138. $queue = DrupalQueue::get($queue);
  139. for ($i=1; $i <= $num_items; $i++) {
  140. $item = new stdClass();
  141. $item->created = time();
  142. $item->sequence = $i;
  143. $queue->createItem($item);
  144. }
  145. }
  146. /**
  147. * Implements hook_cron().
  148. *
  149. * hook_cron() is the traditional (pre-Drupal 7) hook for doing "background"
  150. * processing. It gets called every time the Drupal cron runs and must decide
  151. * what it will do.
  152. *
  153. * In this example, it does a watchdog() call after the time named in
  154. * the variable 'cron_example_next_execution' has arrived, and then it
  155. * resets that variable to a time in the future.
  156. */
  157. function cron_example_cron() {
  158. // Default to an hourly interval. Of course, cron has to be running at least
  159. // hourly for this to work.
  160. $interval = variable_get('cron_example_interval', 60*60);
  161. // We usually don't want to act every time cron runs (which could be every
  162. // minute) so keep a time for the next run in a variable.
  163. if (time() >= variable_get('cron_example_next_execution', 0)) {
  164. // This is a silly example of a cron job.
  165. // It just makes it obvious that the job has run without
  166. // making any changes to your database.
  167. watchdog('cron_example', 'cron_example ran');
  168. if (!empty($GLOBALS['cron_example_show_status_message'])) {
  169. drupal_set_message(t('cron_example executed at %time', array('%time' => date_iso8601(time(0)))));
  170. }
  171. variable_set('cron_example_next_execution', time() + $interval);
  172. }
  173. }
  174. /**
  175. * Implements hook_cron_queue_info().
  176. *
  177. * hook_cron_queue_info() and family are new since Drupal 7, and allow any
  178. * process to add work to the queue to be acted on when cron runs. Queues are
  179. * described and worker callbacks are provided, and then only the worker
  180. * callback needs to be implemented.
  181. *
  182. * All the details of queue use are done by the cron_queue implementation, so
  183. * one doesn't need to know much about DrupalQueue().
  184. *
  185. * @see queue_example.module
  186. */
  187. function cron_example_cron_queue_info() {
  188. $queues['cron_example_queue_1'] = array(
  189. 'worker callback' => 'cron_example_queue_1_worker',
  190. 'time' => 1, // One second max runtime per cron run.
  191. );
  192. $queues['cron_example_queue_2'] = array(
  193. 'worker callback' => 'cron_example_queue_2_worker',
  194. 'time' => 10,
  195. );
  196. return $queues;
  197. }
  198. /**
  199. * Simple workers for the two queues.
  200. *
  201. * @param $item
  202. * Any object to be worked on.
  203. */
  204. function cron_example_queue_1_worker($item) {
  205. cron_example_queue_report_work(1, $item);
  206. }
  207. function cron_example_queue_2_worker($item) {
  208. cron_example_queue_report_work(2, $item);
  209. }
  210. /**
  211. * Simple reporter for the workers.
  212. *
  213. * @param $worker
  214. * (integer) worker number
  215. * @param $item
  216. * (object) the $item which was stored in the cron queue.
  217. */
  218. function cron_example_queue_report_work($worker, $item) {
  219. if (!empty($GLOBALS['cron_example_show_status_message'])) {
  220. drupal_set_message(t('Queue @worker worker processed item with sequence @sequence created at @time', array('@worker' => $worker, '@sequence' => $item->sequence, '@time' => date_iso8601($item->created))));
  221. }
  222. watchdog('cron_example', 'Queue @worker worker processed item with sequence @sequence created at @time', array('@worker' => $worker, '@sequence' => $item->sequence, '@time' => date_iso8601($item->created)));
  223. }
  224. /**
  225. * @} End of "defgroup cron_example".
  226. */