Moodle cron php как запустить
Перейти к содержимому

Moodle cron php как запустить

  • автор:

Moodle cron php как запустить

The Moodle ‘cron’ process is a PHP script (part of the standard Moodle installation) that must be run regularly in the background. The Moodle cron script runs different tasks at differently scheduled intervals.

IMPORTANT: Do not skip setting up the cron process on your server for your Moodle. Your site will not work properly without it.

A special program (typically called — not surprisingly — ‘cron’) is used to run the Moodle cron script at a regular interval. The Moodle cron script runs tasks include sending mail, updating Moodle reports, RSS feeds, activity completions, posting forum messages and other tasks. Since different tasks have different schedules, not every task will run in Moodle when the cron script is triggered.

The cron program (that runs the Moodle script) is a core part of Unix based systems (including Linux and OSX) being used to run all manner of time-dependent services. On Windows the simplest solution is to create a task in the Windows Task Scheduler and set it to run at regular intervals. On shared hosting, you should find the documentation (or ask support) how cron is configured.

Essentially, the task involves adding a single command to the list of cron activities on your system. On Unix based systems this list is a file called a ‘crontab’ which all users have.

Working out the Moodle cron command¶

Moodle has two different ways to deploy cron which use different scripts within the Moodle install. These are as follows.

  1. The CLI (command line interpreter) script. This will be at the path

If in doubt, this is the correct script to use. This needs to be run by a ‘PHP CLI’ program on your computer. So the final command may look something like

/usr/bin/php /path/to/moodle/admin/cli/cron.php

You can (and should) try this on your command line to see if it works.

The web based script. This needs to be run from a web browser and will be accessed via a web url something like http://your.moodle.site/admin/cron.php. You can find command line based web browser (e.g. wget) so the final command may look like

/usr/bin/wget http://your.moodle.site/admin/cron.php

This has the advantage that it can be run from anywhere. If you can’t get cron to work on your machine it can be run somewhere else.

Cron Settings¶

Location: Administration > Site administration > Security > Site Policies

Moodle has two settings where the site administrator can have some control of how the Moodle cron process is triggered. This is done from the Site Policies link.

Cron execution fron command line interface only¶

The cronclionly setting will stop the browser URL Moodle cron process trigger. For example, the site administrator or others running http:demo.moodle.net/admin/cron.php from their web browser.

See the template on the right for assistance with how to create scripts in different operating systems.

Cron password¶

The cron process can be protected by a password with the cronremotepassword setting.

Poodll Support Center

Cron is a system for running scripts or commands on a defined scheduled on the server. Moodle uses it to send out forum emails, delete old files, check for updates on Moodle.org etc. PoodLL uses it to convert audio and video to playable formats in a background task. Whenever you or a student records a video, the next time cron runs, it converts the audio/video and copies it into Moodle. Ideally cron should be run once a minute. Moodle won’t do everything once a minute. It schedules jobs to run at different intervals. Read more about Moodle cron here.

To run the Moodle cron script manually, the command that needs to be run is:

so it might look like this on a typical server:

But that is just the command. You need to schedule it to run each minute ideally. And thats the cron part of things. You can do that via:

  • cPanel
    OR
  • command line.

Using cPanel

From the cPanel’s “advanced” section choose “cron jobs” and add the job with the command there. Like this:

Using command line

From the command line you open the file that contains all the cron jobs, using the cron job editor thingy. If it is the first time you might be asked which command line editor to use. Nano is the easiest. [good luck]

Ideally you will run crontab as the web server user. In that case this command will usually be correct

and add something like this:

After you save it, the cron tasks will be reloaded and your cron job should run … hopefully.

PROИТ

Office 365, AD, Active Directory, Sharepoint, C#, Powershell. Технические статьи и заметки.

Настройка запуска Cron Moodle в Windows Server 2012R2

Дано: система электронного обучения LMS Moodle установлена в IIS на Windows Server 2012 R2.
Задача: настроить периодический запуск специального файла cron.php

Что такое cron в Moodle и почему он важен? Это специальная сервисная процедура, которая обслуживает процессы, происходящие в системе мудл, такие как очистка данных, резервирование, отправка оповещений и т.п. Если ее не запускать, то нормальная работа система может быть нарушена.

Если крон не запускался более суток, то администратор увидит об этом сообщение, если перейдет в административном меню по ссылке «Уведомления«:

Cron должен запускаться как можно чаще, обычно рекомендуют устанавливать периодичность запуска каждые 5 минут.

Крон может запускаться как из браузера, так и прямым доступом к его файлу: cron.php.

Например, можно проверить работу крона перейдя по адресу:
<URL-адрес Moodle>/admin/cron.php

Если при переходе по данному адресу появилось сообщение: «. Извините, доступ к этой странице через интернет заблокирован администратором. . » , то значит возможность запуска крона из браузера заблокирована.

Желательно, чтобы возможность запуска крона из браузера была отключена в целях безопасности. Чтобы это сделать, в административном меню Moodle переходим:
/ Администрирование
/ Безопасность
/ Политика безопасности сайта

На открывшейся странице находим и устанавливаем параметр «Запуск cron только из командной строки (cronclionly)»
Если этот параметр установлен, то cron может быть запущен только из командной строки, а не через веб-интерфейс.

Теперь необходимо настроить запуск крона из командной строки.

На странице официальной документации — https://docs.moodle.org/29/en/Cron_with_Windows_OS как самый быстрый способ настройки — предлагают установить специальную утилиту, которая создаст службу в системе Windows. Однако данная служба будет запускать крон из браузера, а мы эту возможность отключили. Поэтому способ не подходит.

Запуск крона будем настраивать через стандартный планировщик системы Windows — Task Scheduler.

Предварительно создайте пользователя в системе, например, usercron. Его учетную запись будем использовать для запуска процесса крона. Для создания системного профиля один раз заходим под этим пользователем в систему.
Также даем право modify данному пользователю на папку с данными Moodle.

Далее создаем bat-файл (например, cron.bat) со следующим содержимым (скриптом):

В данном скрипте необходимо правильно задать пути:
PathPHP — путь к запускному файлу php (его можно посмотреть по кнопке PHP Manager в IIS)
PathCron — абсолютный путь к файлу крона: <путь папки с Moodle>\admin\cli\cron.php
PathLOG — любое место, куда будут записываться логи крона

Данный скрипт запускает крон по указанному пути, результат его работы записывает в лог-файл, а также удаляет логи старше 5 дней.

Для проверки можно запустить данный скрипт от имени созданного ранее пользователя, чтобы заранее выявить возможные ошибки.

При отработке крона в логах можно обнаружить такую ошибку:
Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.
Это означает, что пользователю usercron не заданы права записи на Moodle-папку для хранения данных. Задайте права, если Вы забыли это сделать.

Далее необходимо настроить планировщик таким образом, чтобы данный скрипт запускался, допустим, каждые 10 минут (либо можете настроить на каждые 5 минут).

Открываем встроенный планировщик Windows (Task Scheduler) и добавляем новую задачу:

На вкладке General новой задачи задаем поля имени задачи.
В блоке Security options нажимаем «Change User…» и указываем ранее созданного пользователя (usercron), задавая таким образом пользователя для запуска задачи.
Также выбираем параметр «Run whether user is logged on or not«, чтобы задача выполнялась всегда, не зависимо от того, залогинен наш пользователь или нет.
Конфигурацию указываем — Windows Server 2012 R2:

На вкладке Триггеры (Triggers) нужно будет задать периодичность запуска задачи. Нажимаем кнопку New и настраиваем расписание запуска (я поставила на каждые 10 минут):

На вкладке Действия (Action) задаем, что нужно сделать. Нажимаем кнопку New и выбираем «Start a program«, а в поле «Program/script» указываем путь к только что созданному bat-файлу:

На вкладке Условия (Conditions) оставляем всё по умолчанию:

Настраиваем под себя вкладку Настройки (Settings):

После нажатия на ОК попросят ввести пароль указанного ранее пользователя, а затем может возникнуть сообщение:
This task requires that the user account specified has Log on as batch job rights

Это означает, что пользователю необходимо предоставить право регистрироваться для запуска пакета команд.

Если проигнорировать это сообщение, то при запуске задания будет возникать ошибка:
Task Scheduler failed to start «\Moodle Cron Service» task for user «ServerName\usercron». Additional Data: Error Value: 2147943785 .

Нам нужно предоставить дополнительные привилегии для нашего пользователя (usercron). Для того запускаем в системе оснастку Local Security Policy:

В открывшемся окне находим ветку «Local Policies — User Rights Assignment«:

Открываем настройку «Log on as a batch job» и к уже имеющемуся списку пользователей добавляем нашего usercron (по кнопке Add User or Group):

После этого запускаем нашу задачу в планировщике. По лог-файлам можно отследить ход выполнения процедуры cron. Через 5 дней желательно проверить, что старые логи удаляются, согласно заданному скрипту.

Getting Started!

hamza khatana

To get started, first we need to know about the Cron job concept and the prerequisites for doing this task. let’s discuss Cron job briefly.

What is the Corn job?

The word Cron is a Greek word that means time, and Cron/Cron job is also somehow associated with time. This is a software utility that is the time-based task scheduler in Unix-like operating systems. Users who set up and maintain software environments use Cron to schedule jobs(commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates the system maintenance, backup process, administrations, reports generation for admin users, etc.

Why do we run Cron job for Moodle?

Moodle is an open-source Learning Management System(system) that needs to automate many tasks to manage the administration of LMS smoothly. In LMS setup admin needs to schedule many tasks like:

  • updating reports such as quiz, admin, gradebook
  • updating course and activity completion (if enabled in advanced settings)
  • updating portfolio
  • plagiarism checks
  • updates activity modules
  • updates blocks
  • create the backups of courses at the time specified in the administration settings.
  • updating messaging module or forum email notifications.
  • unenroll students — this is done on a random basis about 20% of the time Moodle’s Cron process is triggered.
  • deleting users who have not filled out their profile via the 20% random trigger
  • deleting old logs are also checked 20% of the time via the 20% random trigger
  • deletes old cached text
  • generates new passwords for new users and notifies users
  • runs authentication enrolments processes
  • updates stats if enabled.
  • runs blog clean-ups
  • updates registrations

How many ways to run a Cron job for Moodle?

There are two ways to run the Cron job for moodle:

  • The command line (CLI) Cron
  • Web-based Cron

Now we will only discuss CLI Cron that we will set up using Linux commands.

Where can we find Script for tasks to be Scheduled?

The script cron.php can be found in Moodle installation directory at the following address(only if Moodle is installed on Linux)

/path to Moodle/admin/cli/cron.php

(usually path to moodle is = /var/www/html/moodle )

Pre-requisites for running Cron-job

To start with this process one must have:

  • Moodle must be installed on Unix-based systems
  • User must have the root privileges
  • Must have the path to PHP by executing which PHP

Let’s start!

To run the Cron job we first have to navigate to our Moodle project directory and then we will run the following command to open crontab in an editor to enter the commands to schedule the cron.php execution.

sudo crontab -u www-data -e

This will open a text editor which looks like this:

Now we will enter the following command:
* * * * * /path to PHP /path to moodle/admin/cli/cron.php >/dev/null
here use the path to PHP that is /usr/bin/php and path to moodle installation directory.
let’s break the command and understand it in detail.
* * * * * are the first five entries that define the time.

The above snippet is taken from crontab.guru which clearly explains the format of time that we can set using these five entries. as from the above image we can see that first, second, third, fourth, and fifth stands for minutes, hours, days, month and year respectively.

Now using this format we can set the scheduling time. let’s say we want our script to be executed at 10 pm every day, then our command will be:

* 22 * * * /path to PHP /path to moodle/admin/cli/cron.php >/dev/null

Note: the time is in 24 hrs format.

Next in the command is the path to PHP followed by the path to cron.php and terminated with EOF indicator i.e. ( >/dev/null )

Now save and close the file and we are now successful in scheduling the Cron job to be executed at 10 pm on the daily basis.

Concluding Remarks

In this article, we learned about the Unix-based command(Cron job) that makes things easier for the Moodle administrator by automating a lot of software services on daily basis.

Any type of queries related to this article is welcome. Hope you people will find it helpful.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *