PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Examples/Tasks/ParallelTasks.php

http://github.com/shaneharter/PHP-Daemon
PHP | 75 lines | 42 code | 12 blank | 21 comment | 10 complexity | 172ead132d083f534172c0d42ad1d8ed MD5 | raw file
  1. <?php
  2. namespace Examples\Tasks;
  3. class ParallelTasks extends \Core_Daemon
  4. {
  5. protected $loop_interval = 1;
  6. /**
  7. * The only plugin we're using is a simple file-based lock to prevent 2 instances from running
  8. */
  9. protected function setup_plugins()
  10. {
  11. $this->plugin('Lock_File');
  12. }
  13. /**
  14. * This is where you implement any once-per-execution setup code.
  15. * @return void
  16. * @throws \Exception
  17. */
  18. protected function setup()
  19. {
  20. }
  21. /**
  22. * This is where you implement the tasks you want your daemon to perform.
  23. * This method is called at the frequency defined by loop_interval.
  24. *
  25. * @return void
  26. */
  27. protected function execute()
  28. {
  29. // Randomly Create Background Tasks
  30. if (mt_rand(1, 20) == 1) {
  31. $this->log("Creating Sleepy Task");
  32. $this->task(array($this, 'task_sleep'));
  33. }
  34. if (mt_rand(1, 40) == 1) {
  35. $sleepfor = mt_rand(60, 180);
  36. $this->task(new BigTask($sleepfor, "I just woke up from my {$sleepfor} second sleep"));
  37. }
  38. // Randomly Shut Down -- Demonstrate daemon shutdown behavior while background tasks are running
  39. if (mt_rand(1, 1000) == 1) {
  40. $this->log("Shutting Down..");
  41. $this->shutdown(true);
  42. }
  43. }
  44. protected function task_sleep()
  45. {
  46. $this->log("Sleeping For 20 Seconds");
  47. sleep(20);
  48. }
  49. /**
  50. * Dynamically build the file name for the log file. This simple algorithm
  51. * will rotate the logs once per day and try to keep them in a central /var/log location.
  52. * @return string
  53. */
  54. protected function log_file()
  55. {
  56. $dir = '/var/log/daemons/paralleltasks';
  57. if (@file_exists($dir) == false)
  58. @mkdir($dir, 0777, true);
  59. if (@is_writable($dir) == false)
  60. $dir = BASE_PATH . '/example_logs';
  61. return $dir . '/log_' . date('Ymd');
  62. }
  63. }