cronish.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * GNU social cron-on-visit class
  18. *
  19. * Keeps track, through Config dataobject class, of relative time since the
  20. * last run in order to to run event handlers with certain intervals.
  21. *
  22. * @category Cron
  23. * @package GNUsocial
  24. * @author Mikael Nordfeldth <mmn@hethane.se>
  25. * @copyright 2013 Free Software Foundation, Inc http://www.fsf.or
  26. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  27. */
  28. defined('GNUSOCIAL') || die();
  29. class Cronish
  30. {
  31. /**
  32. * Will call events as close as it gets to one hour. Event handlers
  33. * which use this MUST be as quick as possible, maybe only adding a
  34. * queue item to be handled later or something. Otherwise execution
  35. * will timeout for PHP - or at least cause unnecessary delays for
  36. * the unlucky user who visits the site exactly at one of these events.
  37. */
  38. public function callTimedEvents()
  39. {
  40. $timers = array('minutely' => 60, // this is NOT guaranteed to run every minute (only on busy sites)
  41. 'hourly' => 3600,
  42. 'daily' => 86400,
  43. 'weekly' => 604800);
  44. foreach ($timers as $name => $interval) {
  45. $run = false;
  46. $lastrun = new Config();
  47. $lastrun->section = 'cron';
  48. $lastrun->setting = 'last_' . $name;
  49. $found = $lastrun->find(true);
  50. if (!$found) {
  51. $lastrun->value = hrtime(true);
  52. if ($lastrun->insert() === false) {
  53. common_log(LOG_WARNING, "Could not save 'cron' setting '{$name}'");
  54. continue;
  55. }
  56. $run = true;
  57. } elseif ($lastrun->value < hrtime(true) - $interval * 1000000000) {
  58. $orig = clone($lastrun);
  59. $lastrun->value = hrtime(true);
  60. $lastrun->update($orig);
  61. $run = true;
  62. }
  63. if ($run === true) {
  64. // such as CronHourly, CronDaily, CronWeekly
  65. Event::handle('Cron' . ucfirst($name));
  66. }
  67. }
  68. }
  69. }