окончательное редактирование: я переместил это в 406 Ошибка GET Cron Job?
РЕДАКТИРОВАТЬ 4:
я получаю страницу с ошибкой 406 с этим cron!
вот crontab (скопировано из cPanel):
* * * * * GET https://abc.com/cron/sendBulletinEmails.php >>
/home/abc/public_html/cron/logs/sendBulletinEmails.log
вот журнал:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>406 Not Acceptable</title>
</head><body>
<h1>Not Acceptable</h1>
<p>An appropriate representation of the requested resource /cron/sendSurveyEmails.php could not be found on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
У меня установлен php на виртуальной машине под управлением Linux. я установил свой crontab на:
* * * * * { cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails
однако похоже, что cron не работает. он не регистрирует никаких ошибок и не отправляет электронные письма. ты знаешь что не так?
Спасибо!
РЕДАКТИРОВАТЬ 3:
Я нашел журналы работы cron. Кажется, все в порядке, но он все еще не работает и ничего не выводит!
Aug 5 16:20:01 fiqsrv1 CRON[18543]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:21:01 fiqsrv1 CRON[18549]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:22:01 fiqsrv1 CRON[18554]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:23:01 fiqsrv1 CRON[18559]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:24:01 fiqsrv1 CRON[18564]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:25:01 fiqsrv1 CRON[18569]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:26:01 fiqsrv1 CRON[18574]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:27:01 fiqsrv1 CRON[18595]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:28:01 fiqsrv1 CRON[18601]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
Aug 5 16:29:01 fiqsrv1 CRON[18610]: (cgurnik) CMD ({ cd /var/www/cron && /usr/bin/php -f sendQueuedEmails.php ;} |/usr/bin/logger -t sendQueuedEmails)
РЕДАКТИРОВАТЬ 2:
теперь, когда я запускаю скрипт, он ничего не выводит.
Я думал, что опубликую сценарий, чтобы показать, что он ВСЕГДА что-то выводит, поэтому я запутался, когда я запускаю его, и ничего не выходит (нет ошибок, нет вывода)
<?php
require '../includes/common.php';
/*
* check that this cron job isn't already running (it can take a long time if there is a large email load, which it is meant for)
* if it is running, end the script
* if it is not running, continue
* set the global variable for this cron job to on
* get all queued emails that have their time to be sent in the past (and so they should be mailed out now)
* loop through them, checking to see if the user is still set to receive the email, and if so, sending it to them
* set the global variable for this cron job to off
*
* JUST IN CASE: put the script in a try catch after the email cron is set to running in globalvars so that it is always reset, even upon failure
*/
// check that this cron job isn't already running (it can take a long time if there is a large email load, which it is meant for)
if(GlobalVars::isEmailCronRunning()) {
echo "Already running! Aborted.";
exit; // if it is running, end the script
}
// if it is not running, continue
// set the global variable for this cron job to on
GlobalVars::set(GlobalVars::VAR_IS_EMAIL_CRON_RUNNING, 1);
try {
// get all queued emails that have their time to be sent in the past (and so they should be mailed out now)
$queuedEmails = Emails::getAllQueuedToSend();
// loop through them, checking to see if the user is still set to receive the email, and if so, sending it to them
$numEmailsSent = 0;
$numEmailsRecalled = 0;
foreach($queuedEmails as $email) {
if(Emails::shouldBeSentToUser($email)) {
Emails::sendQueuedEmail($email[Emails::id]);
$numEmailsSent++;
} else {
Emails::update($email[Emails::id], array(Emails::result => Emails::RESULT_NOT_SENT) );
$numEmailsRecalled++;
}
}
// set the global variable for this cron job to off
GlobalVars::set(GlobalVars::VAR_IS_EMAIL_CRON_RUNNING, 0);
} catch (Exception $e) {
// set the global variable for this cron job to off
GlobalVars::set(GlobalVars::VAR_IS_EMAIL_CRON_RUNNING, 0);
echo "Error: " . print_r($e);
}
if($numEmailsSent || $numEmailsRecalled) {
$details = "Sent " . $numEmailsSent . ". Recalled " . $numEmailsRecalled . ".";
echo nl2br($details);
ActionLogs::add(ActionLogs::CAT_CRON_JOBS, ActionLogs::TYPE_CRON_EMAILER_RUN, $details);
} else {
echo "No emails were sent.";
}
?>
РЕДАКТИРОВАТЬ: я попытался запустить его и получил следующее:
Warning: require_once(/includes/Swift-4.0.6/lib/swift_required.php): failed to open stream: No such file or directory in /var/www/includes/common.php on line 31
Fatal error: require_once(): Failed opening required '/includes/Swift-4.0.6/lib/swift_required.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/includes/common.php on line 31
как я могу установить путь включения, чтобы он работал как на моем сервере отладки Linux, так и на моем живом сервере Linux?
Вы можете использовать веб-версию в cron, если на сервере установлен GET (lwp-request) или curl
ПОЛУЧИТЬ
* * * * * GET http://localhost/cron/sendQueuedEmails.php > /dev/null
завиток
* * * * * curl -o /dev/null http://localhost/cron/sendQueuedEmails.php
Прислушайся к моему совету, кузнечик! Был здесь, сделал это. Сделайте это простым способом и используйте cgi-версию php "/ usr / bin / php-cgi". Если у вас его нет, установите "apt-get install php5-cgi"
Не верите мне? Попробуй это.
В вашем каталоге создайте текстовый файл с именем test.txt и добавьте внутрь произвольный текст. Теперь создайте новый каталог с именем test и файл внутри него с именем test.php, затем добавьте этот код:
<?php
include '../test.txt';
?>
Ваша структура каталогов должна выглядеть примерно так:
/yourdirectory
/yourdirectory/test.txt
/yourdirectory/test/test.php
Перейдите в корневой каталог «cd /» и запустите его из командной строки:
/ usr / bin / php -f /yourdirectory/test/test.php
а потом
/ usr / bin / php-cgi -f /yourdirectory/test/test.php
Увидеть разницу?
Более простой способ проверить, работает ли строка с cron
:
env -i bash -i /dev/null <actual command>
Проверьте / var / log / cron и посмотрите, действительно ли он запускается. Если это так, попробуйте sudo -u, чтобы увидеть, не выдает ли он ошибки.
Также - я бы попробовал использовать полный путь к исполняемому файлу php. Обычно это «/ usr / bin / php», но вы можете ввести «which php», чтобы дважды проверить это для вашей системы.
Ваши записи будут выглядеть примерно так:
Кроме того, если вы меняете каталог только так, чтобы файлы находились в текущем каталоге, вы всегда можете изменить cron следующим образом:
Надеюсь это поможет.
Прямо сейчас эти сценарии могут отправлять свой вывод в битовый пакет, и вы не узнаете, почему они не работают. Возможно, ваши cronjobs не настроены для отправки электронной почты, или электронная почта в системе может не работать.
Я не поклонник отправки вывода cron по электронной почте, отчасти потому, что люди всегда думают, что можно спамить вывод в «root», и я тот, кто получает это письмо. Поскольку в большинстве случаев мы говорим об 1-2 строках вывода, я предлагаю вам записывать вывод ваших cronjobs в syslog.
* * * * * { cd /var/www/cron && php -f sendBulletinEmails.php ;} |/usr/bin/logger -t sendBulletinEmails
* * * * * { cd /var/www/cron && php -f sendSurveyEmails.php ;} |/usr/bin/logger -t sendSurveyEmails
Добавьте папку, содержащую папку "includes", в свой путь включения. Чтобы найти его использование locate swift_required.php
Исходя из вашего исходного вопроса и опубликованного вами кода, вам не хватает строки shebang, которая вам понадобится для запуска вашего PHP-скрипта таким образом. Попробуйте изменить первые несколько строк на это:
#!/usr/local/bin/php5 -q
<?php
// your script here
?>
И у вас должен быть успех.
Конечно, замените / usr / local / bin на правильный путь к вашей установке PHP. Это может / может быть не то же самое. Эта начальная строка нужна вам только для запуска ее как задания cron, а не если вы запускаете ее из браузера.
Эй ... как это висит, эсса? Вот два решения вашей проблемы.
include '../somefile.php' должен включать '/somedir/somefile.php'
Также прочтите этот раздел руководства по php, уделяя особое внимание различиям cli и cgi.
http://www.php.net/manual/en/features.commandline.differences.php
CLI SAPI не меняет текущий каталог на каталог выполненного скрипта!
Пип @ss!