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

Documentation

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.

It is recommended that the cron is run every minute, as required for asynchronous activity deletion when using the recycle bin.

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. Most shared hosting systems use CPanel to manage sites, and usually will have a section for Cron Jobs on the panel.

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.

Contents

General discussion

See the later sections for your server type; this section contains some general background information.

There are essentially two steps to implementing cron:

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.

The web based Moodle cron command

Finding the right place to put the command

This really does depend on the system you are using and you should find and read the documentation for your platform or hosting. In most cases getting the Moodle cron to run consists of establishing the correct command (above) and then adding it, and the time to run the command, to some sort of file. This might be either through a specific user interface or by editing the file directly.

If using the CLI version you also need to make sure that the cron process is run as the correct user. This is not an issue with the web version.

Example. installing cron on Ubuntu/Debian Linux. Assuming logged in as root..

use the crontab command to open a crontab editor window for the www-data user. This is the user that Apache (the web server) runs as on Debian based systems

This will open an editor window. To run the cli cron script every 1 minute, add the line:

NOTE: the final >/dev/null sends all the output to the ‘bin’ and stops you getting an email every 1 minute.

Setting up cron on your system

Choose the information for your server type:

Here are some more instructions for specific hosts (please check that these are up to date):

Using third party cron service

Besides using cron hosted on your own server, you may use third party cron service (usually called webcron):

Cron settings in Moodle

An admin can set cron execution via command line only or a cron password for remote access in ‘Site security settings’ in the Site administration.

Remote cron

Using the ‘web based’ version of cron it is perfectly ok to place the cron process on a different machine to the Moodle server. For example, the cron service on a Unix server can invoke the cron web ‘page’ on a Windows based Moodle server.

Scheduling tasks

An administrator can schedule cron tasks very precisely from Administration > Site administration > Server > Scheduled tasks, see Scheduled tasks

Running cron for several Moodle servers

Debugging Scheduled Tasks

Logging and monitoring

Ideally you should also be logging the output of cron somewhere and monitoring it for issues. You can monitor the overall status of cron to make sure there are no errors by visiting:

Site administration / Reports / System status (/report/status/index.php)

You can also wire this status report up to tools like Icinga / Nagios using the Check API (https://docs.moodle.org/dev/Check_API) cli commands or with the help of plugins like https://github.com/catalyst/moodle-tool_heartbeat.

If there are errors then you can get more details for recently run tasks from the Logs column on the Scheduled task page, but this won’t show ad hoc task failures:

Site administration / Server / Tasks / Scheduled tasks (/admin/tool/task/scheduledtasks.php)

To see ad hoc task failures you either need to rerun the task manually yourself and see the errors, or you need to have already collected the logs for review. For a Moodle running on a single box you could log to a simple log file, or for a cluster you might want to use syslogd or similar, e.g.:

Low latency adhoc tasks

Each time cron is run, after the scheduled tasks the ad hoc tasks are also run. While scheduled tasks can run at most once a minute, ad hoc tasks can be queued at any moment, and generally you want them processed as soon as possible and to not have to wait for the scheduled task to run first. If you only run the normal admin/cli/cron.php then not only might it have to wait to process all the scheduled tasks first, if it has already finished you will have to wait until the next minute for cron to start again for it to be processed.

Instead you can run one or more dedicated ad hoc task processors which run in parallel to the main cron process.

Starting from Moodle 3.9 the—keep-alive option runs like a daemon so when the queue is empty rather than exiting it waits for new tasks to be queued so it can start processing as soon as possible.

Scaling up cron with multiple processes

As your site grows many of the scheduled tasks will take longer to complete, and also there will be more ad hoc tasks queued which need to be processed. The cron system is designed to work in parallel but each individual process can only process one task at a time so you must run multiple cron cli’s. You can generally run a fairly high number of cron processes on a dedicated cron instance before needing to run multiple cron instances. To run more than one process simply spawn multiple cron processes each minute:

It can be especially important to increase the number of adhoc_task.php processes as certain plugins and systems can generate very large numbers of ad hoc tasks, or tasks that can take a long time to process. Especially tasks like document conversions and automated backups can build up more quickly than they are processed if they are left on default settings.

By default only 3 scheduled tasks and 3 ad hoc tasks can be run concurrently so as you add more processes you need to increase the level of allowed concurrency:

Site administration > Server > Tasks > Task processing

Whatever you set these too make sure the server(s) hosting them can comfortably handle this many processes. Often the bottleneck will be a shared service, usually the database.

You may find that certain types of very long running tasks will consume all the available task processes which means no other tasks will run. e.g. if you have 5 cli processes, but in the task queue there are 20 ad hoc tasks for an automated backup, each of which will take ten minutes to complete, then very quickly all 5 processes will be consumed by backups and nothing else. Other small very fast and light tasks like a document conversion or forum emails will not get sent until the backups are complete and a process frees up. To manage this you can limit the concurrency of specific types of ad hoc tasks. A good rule of thumb is that if all of the ‘heavy’ tasks consume all of their own limits then you should still have another few processes standing by on idle waiting for anything else which may be added to the queue.

Automated backups are the worst known offender, so hypothetically if you are running 50 ad hoc task processes concurrently a reasonable restriction might be to cap the backups to consume no more than half of those processes, ie 25 at most:

See also

Источник

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

Правильно настроил cron для Moodle

cron.php запускает отправку почты, обновление отчетов Moodle, RSS-каналов, завершение действий, размещение сообщений на форуме и другие задачи.

По сути, все дело состоит в том, чтобы добавить одну команду в список операций cron в вашей системе. В системах на основе Unix этот список представляет собой файл под названием «crontab», который есть у всех пользователей.

Оптимизация таблиц базы данных в PHPMyAdmin

Оптимизация таблиц или дефрагментация индексов таблиц необходима, так как в базе данных Moodle постоянно добавляются и удаляются данные (записи). Проще говоря оптимизация таблиц БД позволяет убрать «пустые» ключи, тем самым ускоряя в будущем операции выборки, а так же уменьшает общий размер базы данных.

Чтобы выполнить оптимизацию таблиц в phpMyAdmin необходимо:moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

Рекомендуется хотя бы раз в месяц проводить дефрагментацию таблиц на таких сайтах как электронные магазины, форумы, блоги.

В моем случае, общий размер таблиц базы данных уменьшился с 253,5Mb до 204,3Mb.

Ускоряем (оптимизируем) Apache

Включает кэш браузера. Установим модуль Apache mod_expires или mod_headers командами (оба модуля использовать ни к чему):

sudo a2enmod expires

sudo a2enmod headers

перезагрузим сервер Apache:

sudo service apache2 reload

ExpiresActive On
ExpiresDefault «access plus 1 day»
ExpiresByType application/javascript «access plus 1 week»
ExpiresByType image/x-icon «access plus 1 month»
ExpiresByType image/gif «access plus 1 month»
ExpiresByType image/png «access plus 1 month»
ExpiresByType image/jpg «access plus 1 month»
ExpiresByType image/jpeg «access plus 1 month»
ExpiresByType text/css «access plus 1 month»

#10_min

Header set Cache-Control «max-age=600, must-revalidate»

#1_week

Header set Cache-Control «max-age=604800, public»

#1_month

Header set Cache-Control «max-age=2592000, public»

Об этом можно прочесть здесь

Источник

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 и почему он важен? Это специальная сервисная процедура, которая обслуживает процессы, происходящие в системе мудл, такие как очистка данных, резервирование, отправка оповещений и т.п. Если ее не запускать, то нормальная работа система может быть нарушена.

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

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

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

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

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

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

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

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

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

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

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

Источник

Documentation

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.

It is recommended that the cron is run every minute, as required for asynchronous activity deletion when using the recycle bin.

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. Most shared hosting systems use CPanel to manage sites, and usually will have a section for Cron Jobs on the panel.

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.

Contents

General discussion

See the later sections for your server type; this section contains some general background information.

There are essentially two steps to implementing cron:

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.

The web based Moodle cron command

Finding the right place to put the command

This really does depend on the system you are using and you should find and read the documentation for your platform or hosting. In most cases getting the Moodle cron to run consists of establishing the correct command (above) and then adding it, and the time to run the command, to some sort of file. This might be either through a specific user interface or by editing the file directly.

If using the CLI version you also need to make sure that the cron process is run as the correct user. This is not an issue with the web version.

Example. installing cron on Ubuntu/Debian Linux. Assuming logged in as root..

use the crontab command to open a crontab editor window for the www-data user. This is the user that Apache (the web server) runs as on Debian based systems

This will open an editor window. To run the cli cron script every 1 minute, add the line:

NOTE: the final >/dev/null sends all the output to the ‘bin’ and stops you getting an email every 1 minute.

Setting up cron on your system

Choose the information for your server type:

Here are some more instructions for specific hosts (please check that these are up to date):

Using third party cron service

Besides using cron hosted on your own server, you may use third party cron service (usually called webcron):

Cron settings in Moodle

An admin can set cron execution via command line only or a cron password for remote access in ‘Site security settings’ in the Site administration.

Remote cron

Using the ‘web based’ version of cron it is perfectly ok to place the cron process on a different machine to the Moodle server. For example, the cron service on a Unix server can invoke the cron web ‘page’ on a Windows based Moodle server.

Scheduling tasks

An administrator can schedule cron tasks very precisely from Administration > Site administration > Server > Scheduled tasks, see Scheduled tasks

Running cron for several Moodle servers

Debugging Scheduled Tasks

See also

Источник

Запуск PHP скрипта по расписанию cron. Когда не всё так ясно

moodle cron php как запустить. Смотреть фото moodle cron php как запустить. Смотреть картинку moodle cron php как запустить. Картинка про moodle cron php как запустить. Фото moodle cron php как запустить

В этой статье я расскажу о некоторых тонкостях запуска php-скриптов на хостингах, незнание которых может попортить немало нервов и начинающим программистам, и мастерам средней руки.
Причина написания статьи: проблемы с запуском скриптов на хостингах с разными настройками. А поскольку настройки могут быть разными, информация приводимая для общих случаев могут не подходить и приводить в заблуждения.

Немного теории по этим ссылкам: тут и тут, для тех хочет освежить память.

Случай первый


В настройках операционной системы не указаны пути по умолчанию. Как следствие следующая команда в cron не будет выполнена.

Правильной командой будет второй вариант, где мы пропишем полный путь до интерпретатора php.

Есть ещё несколько способов запуска php скрипта описанных здесь. Интересным будет здесь то, что php скрипт запускается как файл с командами для консоли и тут можно написать целую тучу команд и описать всевозможные варианты на любой вкус. Код выглядит так.

В команде для выполнения в cron прописывается путь к скрипту и только. В скрипте ставятся символы #!, а дальше просто пишем нужные нам команды на языке bash.

Случай второй


Выполнение скрипта при запросе из браузера приводит к выводу страницы в браузер. А при выполнении скрипта через cron приводит к выводу текста страницы в командную строку. Тут может быть несколько вариантов. Система может быть настроена на сохранение результатов вывода в консоль в виде файла. Причем файл этот может размешаться не в самом типичном месте. Постепенно это может забить всё пространство на диске. Часто под сайт дают место в 1 Гигабайт, 500 мегабайт. И даже встречались хостинги с 50 и 10 мегабайт под сайт.

Как вариант, вывод может быть перенаправлен на почтовый ящик, который заботливый хостер ненавязчиво подарил вам и прописал в настройках хостинга как email по умолчанию. При каждом выполнении скрипта весь текст, выводящийся в консоль, будет оформлен в письмо. Проблемы могут начаться неожиданно. Если задание cron выполняется часто, а у почты хостинга прописано ограничение на количество писем в день, почта просто ляжет (заблокируется провайдером как потенциальный спамер). И как неприятные последствия вы получите отказ в регистрации пользователей, уведомление пользователей и д.р., что подвязано на почту.

Решение старо как мир. Нужно сделать перенаправление вывода из консоли в пустоту. Делается это добавлением команды в конце команды крона.

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

Случай третий


Ситуация проста. Нужно отладить скрипт, запускаемый планировщиком. Можно попытаться сделать это средствами php, заставлять скрипт писать логии и т.п. Но есть способ куда проще, нужно перенаправить вывод в файл. Команда проста, дополнительный параметр к нашей команде:

Её надо добавить в конце команды:

Знак «>» указывает системе о перенаправлении вывода. Далее имя файла. В нашем случае указан абсолютный путь. Этот пример не составляет труда найти в интернете. Но тут нас может поджидать неприятность, вытекающая из второго случая. Заботливый хостер автоматически добавляет перенаправление вывода в конце нашей строки. И иногда маскирует это. В итоге получается команда вида:

В итоге вывод снова перенаправлен в пустоту и выходной файл будет пуст. Тут хостеру можно указать на его ошибку, что он уж слишком перехитрил с настройками. А можно сразу воспользоваться костылём. После команды перенаправления в файл закончить команду символами &&. Эти два символа используются в командной строке для объединения нескольких команд в одной строке. Они дают командной строке понять, что команда окончена и дальше идет следующая команда. К ней и применяется перенаправление в пустоту. В итоге и перенаправление в пустоту осталось и лог файл записан верно. Пример команды:

Случай четвёртый

Первое, что находишь в интернете по этой проблеме – совет прописать в кроне команду смены директории:

Но в каких-то случаях это не помогает. Выход есть. Один из них взять всё в свои руки и задать недостающее окружение для работы скрипта. Информации про это в интернете уже больше.

Иногда просто хватает вписать следующий код в начале скрипта и пути снова становятся рабочими.

Как видите, всё прописано функциями и утруждаться настройками не надо.

Источник

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

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