cronish.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * GNU social cron-on-visit class
  4. *
  5. * Keeps track, through Config dataobject class, of relative time since the
  6. * last run in order to to run event handlers with certain intervals.
  7. *
  8. * @category Cron
  9. * @package GNUsocial
  10. * @author Mikael Nordfeldth <mmn@hethane.se>
  11. * @copyright 2013 Free Software Foundation, Inc.
  12. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  13. * @link http://status.net/
  14. */
  15. class Cronish
  16. {
  17. /**
  18. * Will call events as close as it gets to one hour. Event handlers
  19. * which use this MUST be as quick as possible, maybe only adding a
  20. * queue item to be handled later or something. Otherwise execution
  21. * will timeout for PHP - or at least cause unnecessary delays for
  22. * the unlucky user who visits the site exactly at one of these events.
  23. */
  24. public function callTimedEvents()
  25. {
  26. $timers = array('minutely' => 60, // this is NOT guaranteed to run every minute (only on busy sites)
  27. 'hourly' => 3600,
  28. 'daily' => 86400,
  29. 'weekly' => 604800);
  30. foreach($timers as $name=>$interval) {
  31. $run = false;
  32. $lastrun = new Config();
  33. $lastrun->section = 'cron';
  34. $lastrun->setting = 'last_' . $name;
  35. $found = $lastrun->find(true);
  36. if (!$found) {
  37. $lastrun->value = time();
  38. if ($lastrun->insert() === false) {
  39. common_log(LOG_WARNING, "Could not save 'cron' setting '{$name}'");
  40. continue;
  41. }
  42. $run = true;
  43. } elseif ($lastrun->value < time() - $interval) {
  44. $orig = clone($lastrun);
  45. $lastrun->value = time();
  46. $lastrun->update($orig);
  47. $run = true;
  48. }
  49. if ($run === true) {
  50. // such as CronHourly, CronDaily, CronWeekly
  51. Event::handle('Cron' . ucfirst($name));
  52. }
  53. }
  54. }
  55. }