public static function queue_adhoc_task(adhoc_task $task, $checkforexisting = false) {
        global $DB;

        if ($userid = $task->get_userid()) {
            // User found. Check that they are suitable.
            \core_user::require_active_user(\core_user::get_user($userid, '*', MUST_EXIST), true, true);
        }

        $record = self::record_from_adhoc_task($task);
        // Schedule it immediately if nextruntime not explicitly set.
        if (!$task->get_next_run_time()) {
            $record->nextruntime = time() - 1;
        }

        // Check if the same task is already scheduled.
        if ($checkforexisting && self::task_is_scheduled($task)) {
            return false;
        }

        // Queue the task.
        $result = $DB->insert_record('task_adhoc', $record);

        return $result;
    }