1. <?php
  2. /**
  3. * Indexes content of time values for short-lived tasks with hard-coded limits.
  4. */
  5. class TaskIndex {
  6. private $taskData = []; // Array to store task data (time value => content)
  7. private $maxTasks = 10; // Maximum number of tasks to store
  8. private $timeWindowSeconds = 60; // Time window in seconds to consider
  9. public function addTask($timestamp, $content) {
  10. // Calculate the time difference from the current time
  11. $timeDiff = time() - $timestamp;
  12. // Check if the task is within the time window
  13. if ($timeDiff <= $this->timeWindowSeconds) {
  14. $this->taskData[$timestamp] = $content; // Store the task data
  15. // Limit the number of tasks stored
  16. if (count($this->taskData) > $this->maxTasks) {
  17. // Remove the oldest task
  18. reset($this->taskData); // Reset the internal pointer to the beginning
  19. if (!empty($this->taskData)) {
  20. unset($this->taskData[key($this->taskData)]); // Remove the oldest entry
  21. }
  22. }
  23. }
  24. }
  25. public function getTaskContent($timestamp) {
  26. // Retrieve the content associated with the given timestamp
  27. return $this->taskData[$timestamp] ?? null; // Return null if not found
  28. }
  29. public function getIndexedTasks() {
  30. // Return the current indexed tasks (for debugging/inspection)
  31. return $this->taskData;
  32. }
  33. }
  34. // Example usage:
  35. $indexer = new TaskIndex();
  36. // Simulate adding tasks at different times
  37. $indexer->addTask(time() - 30, "Task 1");
  38. $indexer->addTask(time() - 10, "Task 2");
  39. $indexer->addTask(time() - 5, "Task 3");
  40. $indexer->addTask(time() - 15, "Task 4");
  41. $indexer->addTask(time() - 20, "Task 5");
  42. $indexer->addTask(time() - 25, "Task 6");
  43. $indexer->addTask(time() - 35, "Task 7");
  44. $indexer->addTask(time() - 40, "Task 8");
  45. $indexer->addTask(time() - 45, "Task 9");
  46. $indexer->addTask(time() - 50, "Task 10");
  47. $indexer->addTask(time() - 55, "Task 11"); // This will replace Task 1
  48. // Retrieve the content of a specific task
  49. $content = $indexer->getTaskContent(time() - 10);
  50. echo "Content of task at time " . (time() - 10) . ": " . ($content ?? "Not found") . "\n";
  51. // Print the indexed tasks
  52. print_r($indexer->getIndexedTasks());
  53. ?>

Add your comment