Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TaskScheduler.php « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6d94d591a11a0ddc0d02ccc8258b5a341609bbc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik;

use Exception;
use Piwik\Plugin\Manager as PluginManager;

// When set to true, all scheduled tasks will be triggered in all requests (careful!)
define('DEBUG_FORCE_SCHEDULED_TASKS', false);

/**
 * Manages scheduled task execution.
 *
 * A scheduled task is a callback that should be executed every so often (such as daily,
 * weekly, monthly, etc.). They are registered with **TaskScheduler** through the
 * {@hook TaskScheduler.getScheduledTasks} event.
 *
 * Tasks are executed when the cron core:archive command is executed.
 *
 * ### Examples
 *
 * **Scheduling a task**
 *
 *     // event handler for TaskScheduler.getScheduledTasks event
 *     public function getScheduledTasks(&$tasks)
 *     {
 *         $tasks[] = new ScheduledTask(
 *             'Piwik\Plugins\CorePluginsAdmin\MarketplaceApiClient',
 *             'clearAllCacheEntries',
 *             null,
 *             ScheduledTime::factory('daily'),
 *             ScheduledTask::LOWEST_PRIORITY
 *         );
 *     }
 *
 * **Executing all pending tasks**
 *
 *     $results = TaskScheduler::runTasks();
 *     $task1Result = $results[0];
 *     $task1Name = $task1Result['task'];
 *     $task1Output = $task1Result['output'];
 *
 *     echo "Executed task '$task1Name'. Task output:\n$task1Output";
 *
 * @method static \Piwik\TaskScheduler getInstance()
 */
class TaskScheduler extends Singleton
{
    const GET_TASKS_EVENT  = 'TaskScheduler.getScheduledTasks';

    private $isRunning = false;

    private $timetable = null;

    public function __construct()
    {
        $this->timetable = new ScheduledTaskTimetable();
    }

    /**
     * Executes tasks that are scheduled to run, then reschedules them.
     *
     * @return array An array describing the results of scheduled task execution. Each element
     *               in the array will have the following format:
     *
     *               ```
     *               array(
     *                   'task' => 'task name',
     *                   'output' => '... task output ...'
     *               )
     *               ```
     */
    public static function runTasks()
    {
        return self::getInstance()->doRunTasks();
    }

    // for backwards compatibility
    private function collectTasksRegisteredViaEvent()
    {
        $tasks = array();

        /**
         * @ignore
         * @deprecated
         */
        Piwik::postEvent(self::GET_TASKS_EVENT, array(&$tasks));

        return $tasks;
    }

    private function getScheduledTasks()
    {
        /** @var \Piwik\ScheduledTask[] $tasks */
        $tasks = $this->collectTasksRegisteredViaEvent();

        /** @var \Piwik\Plugin\Tasks[] $pluginTasks */
        $pluginTasks = PluginManager::getInstance()->findComponents('Tasks', 'Piwik\\Plugin\\Tasks');
        foreach ($pluginTasks as $pluginTask) {

            $pluginTask->schedule();

            foreach ($pluginTask->getScheduledTasks() as $task) {
                $tasks[] = $task;
            }
        }

        return $tasks;
    }

    private function doRunTasks()
    {
        $tasks = $this->getScheduledTasks();

        // remove from timetable tasks that are not active anymore
        $this->timetable->removeInactiveTasks($tasks);

        // for every priority level, starting with the highest and concluding with the lowest
        $executionResults = array();
        for ($priority = ScheduledTask::HIGHEST_PRIORITY;
             $priority <= ScheduledTask::LOWEST_PRIORITY;
             ++$priority) {
            // loop through each task
            foreach ($tasks as $task) {
                // if the task does not have the current priority level, don't execute it yet
                if ($task->getPriority() != $priority) {
                    continue;
                }

                $taskName = $task->getName();
                $shouldExecuteTask = $this->timetable->shouldExecuteTask($taskName);

                if ($this->timetable->taskShouldBeRescheduled($taskName)) {
                    $this->timetable->rescheduleTask($task);
                }

                if ($shouldExecuteTask) {
                    $this->isRunning = true;
                    $message = self::executeTask($task);
                    $this->isRunning = false;

                    $executionResults[] = array('task' => $taskName, 'output' => $message);
                }
            }
        }

        return $executionResults;
    }

    /**
     * Determines a task's scheduled time and persists it, overwriting the previous scheduled time.
     *
     * Call this method if your task's scheduled time has changed due to, for example, an option that
     * was changed.
     *
     * @param ScheduledTask $task Describes the scheduled task being rescheduled.
     * @api
     */
    public static function rescheduleTask(ScheduledTask $task)
    {
        self::getInstance()->timetable->rescheduleTask($task);
    }

    /**
     * Returns true if the TaskScheduler is currently running a scheduled task.
     *
     * @return bool
     */
    public static function isTaskBeingExecuted()
    {
        return self::getInstance()->isRunning;
    }

    /**
     * Return the next scheduled time given the class and method names of a scheduled task.
     *
     * @param string $className The name of the class that contains the scheduled task method.
     * @param string $methodName The name of the scheduled task method.
     * @param string|null $methodParameter Optional method parameter.
     * @return mixed int|bool The time in miliseconds when the scheduled task will be executed
     *                        next or false if it is not scheduled to run.
     */
    public static function getScheduledTimeForMethod($className, $methodName, $methodParameter = null)
    {
        return self::getInstance()->timetable->getScheduledTimeForMethod($className, $methodName, $methodParameter);
    }

    /**
     * Executes the given taks
     *
     * @param ScheduledTask $task
     * @return string
     */
    private static function executeTask($task)
    {
        try {
            $timer = new Timer();
            call_user_func(array($task->getObjectInstance(), $task->getMethodName()), $task->getMethodParameter());
            $message = $timer->__toString();
        } catch (Exception $e) {
            $message = 'ERROR: ' . $e->getMessage();
        }

        return $message;
    }
}