예제 #1
0
 public function check_status(thresholds $thresholds, $params = array())
 {
     if (!isset($params['task'])) {
         throw new invalid_service_exception("Task parameter required");
     }
     if (!($task = \core\task\manager::get_scheduled_task($params['task']))) {
         throw new invalid_service_exception("Task not found");
     }
     $result = new status_result();
     $lastrun = $task->get_last_run_time();
     if (!$lastrun) {
         $result->text = 'Task has never run';
         $result->status = service::NAGIOS_STATUS_UNKNOWN;
     } else {
         $timeelapsed = time() - $lastrun;
         $result->status = $thresholds->check($timeelapsed);
         $result->text = "Last ran at " . date(DATE_RSS, $lastrun) . ", {$timeelapsed} seconds ago";
     }
     return $result;
 }
예제 #2
0
 /**
  * Runs a scheduled task immediately, given full class name.
  *
  * This is faster and more reliable than running cron (running cron won't
  * work more than once in the same test, for instance). However it is
  * a little less 'realistic'.
  *
  * While the task is running, we suppress mtrace output because it makes
  * the Behat result look ugly.
  *
  * Note: Most of the code relating to running a task is based on
  * admin/tool/task/cli/schedule_task.php.
  *
  * @Given /^I run the scheduled task "(?P<task_name>[^"]+)"$/
  * @param string $taskname Name of task e.g. 'mod_whatever\task\do_something'
  */
 public function i_run_the_scheduled_task($taskname)
 {
     $task = \core\task\manager::get_scheduled_task($taskname);
     if (!$task) {
         throw new DriverException('The "' . $taskname . '" scheduled task does not exist');
     }
     // Do setup for cron task.
     raise_memory_limit(MEMORY_EXTRA);
     cron_setup_user();
     // Get lock.
     $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
     if (!($cronlock = $cronlockfactory->get_lock('core_cron', 10))) {
         throw new DriverException('Unable to obtain core_cron lock for scheduled task');
     }
     if (!($lock = $cronlockfactory->get_lock('\\' . get_class($task), 10))) {
         $cronlock->release();
         throw new DriverException('Unable to obtain task lock for scheduled task');
     }
     $task->set_lock($lock);
     if (!$task->is_blocking()) {
         $cronlock->release();
     } else {
         $task->set_cron_lock($cronlock);
     }
     try {
         // Discard task output as not appropriate for Behat output!
         ob_start();
         $task->execute();
         ob_end_clean();
         // Mark task complete.
         \core\task\manager::scheduled_task_complete($task);
     } catch (Exception $e) {
         // Mark task failed and throw exception.
         \core\task\manager::scheduled_task_failed($task);
         throw new DriverException('The "' . $taskname . '" scheduled task failed', 0, $e);
     }
 }
    /**
     * Test that the file_temp_cleanup_task removes directories and
     * files as expected.
     */
    public function test_file_temp_cleanup_task() {
        global $CFG;

        // Create directories.
        $dir = $CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR . 'courses';
        mkdir($dir, 0777, true);

        // Create files to be checked and then deleted.
        $file01 = $dir . DIRECTORY_SEPARATOR . 'sections.xml';
        file_put_contents($file01, 'test data 001');
        $file02 = $dir . DIRECTORY_SEPARATOR . 'modules.xml';
        file_put_contents($file02, 'test data 002');
        // Change the time modified for the first file, to a time that will be deleted by the task (greater than seven days).
        touch($file01, time() - (8 * 24 * 3600));

        $task = \core\task\manager::get_scheduled_task('\\core\\task\\file_temp_cleanup_task');
        $this->assertInstanceOf('\core\task\file_temp_cleanup_task', $task);
        $task->execute();

        // Scan the directory. Only modules.xml should be left.
        $filesarray = scandir($dir);
        $this->assertEquals('modules.xml', $filesarray[2]);
        $this->assertEquals(3, count($filesarray));

        // Change the time modified on modules.xml.
        touch($file02, time() - (8 * 24 * 3600));
        // Change the time modified on the courses directory.
        touch($CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR .
                'courses', time() - (8 * 24 * 3600));
        // Run the scheduled task to remove the file and directory.
        $task->execute();
        $filesarray = scandir($CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01');
        // There should only be two items in the array, '.' and '..'.
        $this->assertEquals(2, count($filesarray));

        // Change the time modified on all of the files and directories.
        $dir = new \RecursiveDirectoryIterator($CFG->tempdir);
        // Show all child nodes prior to their parent.
        $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);

        for ($iter->rewind(); $iter->valid(); $iter->next()) {
            $node = $iter->getRealPath();
            touch($node, time() - (8 * 24 * 3600));
        }

        // Run the scheduled task again to remove all of the files and directories.
        $task->execute();
        $filesarray = scandir($CFG->tempdir);
        // All of the files and directories should be deleted.
        // There should only be two items in the array, '.' and '..'.
        $this->assertEquals(2, count($filesarray));
    }
예제 #4
0
            if ($task->get_disabled()) {
                $nextrun = get_string('taskdisabled', 'tool_task');
            } else {
                if ($nextrun > time()) {
                    $nextrun = userdate($nextrun);
                } else {
                    $nextrun = get_string('asap', 'tool_task');
                }
            }
        }
        echo str_pad($class, 50, ' ') . ' ' . str_pad($schedule, 17, ' ') . ' ' . $nextrun . "\n";
    }
    exit(0);
}
if ($execute = $options['execute']) {
    if (!($task = \core\task\manager::get_scheduled_task($execute))) {
        mtrace("Task '{$execute}' not found");
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        mtrace("Moodle upgrade pending, cannot execute tasks.");
        exit(1);
    }
    // Increase memory limit.
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin account by default.
    cron_setup_user();
    $predbqueries = $DB->perf_get_queries();
    $pretime = microtime(true);
    mtrace("Scheduled task: " . $task->get_name());
    // NOTE: it would be tricky to move this code to \core\task\manager class,
예제 #5
0
 *   - For debugging & better logging, you are encouraged to use in the command line:
 *     -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
 *
 * Performance notes:
 * We have optimized it as best as we could for PostgreSQL and MySQL, with 27K students
 * we have seen this take 10 minutes.
 *
 * @package    auth_cas
 * @copyright  2007 Jerome Gutierrez - based on code by Martin Langhoff
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @deprecated since Moodle 3.0 MDL-51824 - please do not use this CLI script any more, use scheduled task instead.
 * @todo MDL-50264 This will be deleted in Moodle 3.2.
 */
define('CLI_SCRIPT', true);
require __DIR__ . '/../../../config.php';
require_once $CFG->dirroot . '/course/lib.php';
require_once $CFG->libdir . '/clilib.php';
// Ensure errors are well explained
set_debugging(DEBUG_DEVELOPER, true);
if (!is_enabled_auth('cas')) {
    error_log('[AUTH CAS] ' . get_string('pluginnotenabled', 'auth_ldap'));
    die;
}
cli_problem('[AUTH CAS] The sync users cron has been deprecated. Please use the scheduled task instead.');
// Abort execution of the CLI script if the auth_cas\task\sync_task is enabled.
$task = \core\task\manager::get_scheduled_task('auth_cas\\task\\sync_task');
if (!$task->get_disabled()) {
    cli_error('[AUTH CAS] The scheduled task sync_task is enabled, the cron execution has been aborted.');
}
$casauth = get_auth_plugin('cas');
$casauth->sync_users(true);
예제 #6
0
require_once $CFG->libdir . '/tablelib.php';
$PAGE->set_url('/admin/tool/task/scheduledtasks.php');
$PAGE->set_context(context_system::instance());
$PAGE->set_pagelayout('admin');
$strheading = get_string('scheduledtasks', 'tool_task');
$PAGE->set_title($strheading);
$PAGE->set_heading($strheading);
require_login();
require_capability('moodle/site:config', context_system::instance());
$renderer = $PAGE->get_renderer('tool_task');
$action = optional_param('action', '', PARAM_ALPHAEXT);
$taskname = optional_param('task', '', PARAM_RAW);
$task = null;
$mform = null;
if ($taskname) {
    $task = \core\task\manager::get_scheduled_task($taskname);
    if (!$task) {
        print_error('invaliddata');
    }
}
if ($action == 'edit') {
    $PAGE->navbar->add(get_string('edittaskschedule', 'tool_task', $task->get_name()));
}
if ($task) {
    $mform = new tool_task_edit_scheduled_task_form(null, $task);
}
if ($mform && ($mform->is_cancelled() || !empty($CFG->preventscheduledtaskchanges))) {
    redirect(new moodle_url('/admin/tool/task/scheduledtasks.php'));
} else {
    if ($action == 'edit' && empty($CFG->preventscheduledtaskchanges)) {
        if ($data = $mform->get_data()) {
예제 #7
0
 public function test_complete_plans_task()
 {
     global $DB;
     $this->resetAfterTest(true);
     $this->setAdminUser();
     $dg = $this->getDataGenerator();
     $lpg = $dg->get_plugin_generator('core_competency');
     $user = $dg->create_user();
     $up1 = $lpg->create_plan(array('userid' => $user->id, 'status' => \core_competency\plan::STATUS_DRAFT));
     $up2 = $lpg->create_plan(array('userid' => $user->id, 'status' => \core_competency\plan::STATUS_ACTIVE));
     // Set duedate in the past.
     $date = new \DateTime('yesterday');
     $record1 = $up1->to_record();
     $record2 = $up2->to_record();
     $record1->duedate = $date->getTimestamp();
     $record2->duedate = $date->getTimestamp();
     $DB->update_record(plan::TABLE, $record1);
     $DB->update_record(plan::TABLE, $record2);
     $task = \core\task\manager::get_scheduled_task('\\core\\task\\complete_plans_task');
     $this->assertInstanceOf('\\core\\task\\complete_plans_task', $task);
     // Test that draft plan can not be completed on running task.
     $task->execute();
     $plandraft = api::read_plan($up1->get_id());
     $this->assertEquals(\core_competency\plan::STATUS_DRAFT, $plandraft->get_status());
     // Test that active plan can be completed on running task.
     $task->execute();
     $planactive = api::read_plan($up2->get_id());
     $this->assertEquals(\core_competency\plan::STATUS_COMPLETE, $planactive->get_status());
 }
예제 #8
0
 *     -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
 *
 * Performance notes:
 * We have optimized it as best as we could for PostgreSQL and MySQL, with 27K students
 * we have seen this take 10 minutes.
 *
 * @package    auth_ldap
 * @copyright  2004 Martin Langhoff
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @deprecated since Moodle 3.0 MDL-51824 - please do not use this CLI script any more, use scheduled task instead.
 * @todo MDL-50264 This will be deleted in Moodle 3.2.
 */
define('CLI_SCRIPT', true);
require __DIR__ . '/../../../config.php';
// global moodle config file.
require_once $CFG->dirroot . '/course/lib.php';
require_once $CFG->libdir . '/clilib.php';
// Ensure errors are well explained
set_debugging(DEBUG_DEVELOPER, true);
if (!is_enabled_auth('ldap')) {
    error_log('[AUTH LDAP] ' . get_string('pluginnotenabled', 'auth_ldap'));
    die;
}
cli_problem('[AUTH LDAP] The users sync cron has been deprecated. Please use the scheduled task instead.');
// Abort execution of the CLI script if the auth_ldap\task\sync_task is enabled.
$taskdisabled = \core\task\manager::get_scheduled_task('auth_ldap\\task\\sync_task');
if (!$taskdisabled->get_disabled()) {
    cli_error('[AUTH LDAP] The scheduled task sync_task is enabled, the cron execution has been aborted.');
}
$ldapauth = get_auth_plugin('ldap');
$ldapauth->sync_users(true);