Cron reboot не работает

@reboot crontab работает только для root?

man 5 crontab довольно ясно, как использовать crontab для запуска скрипта при загрузке:

Поэтому я с радостью добавил одну строку в свой crontab (под моей учетной записью, а не root):

Но по какой-то причине myscript.sh не запускается при перезагрузке компьютера. (он работает нормально, если я вызываю его из командной строки, поэтому это не проблема с разрешениями)

Чего мне не хватает?

Обновление, чтобы ответить на вопросы @ Anthon:

  1. Версия Oracle-linux: 5.8 (uname: 2.6.32-300.39.2.el5uek # 1 SMP)
  2. Версия Cron: vixie-cron-4.1-81.el5.x86_64
  3. Да, /home это смонтированный раздел. Похоже, это проблема. Как мне обойти это?
  4. В настоящее время myscript.sh выводится только текстовое сообщение в файл в /home/me .

Это может быть немного запутанной темой, потому что существуют разные реализации cron. Также было несколько ошибок, которые нарушали эту функцию, и есть также некоторые случаи использования, когда она просто не будет работать, особенно если вы выполняете выключение / загрузку вместо перезагрузки.

ошибки

Здесь описана одна такая ошибка в Debian под названием: cron: @reboot задания не выполняются . Похоже, это пробило себя и в Ubuntu, что я не могу подтвердить напрямую

Доказательство ошибки в Ubuntu, похоже, подтверждается здесь в этом SO Q & A под названием: @reboot cronjob не выполняется .

комментарий №1: . 3) ваша версия crond может не поддерживать @reboot вы используете vron’s crond? . показать результаты пользователя crontab -l -u

комментарий № 2: . Возможно, было бы неплохо установить его в качестве сценария инициализации, а не полагаться на конкретную версию @reboot cron.

комментарий № 3: . @MarkRoberts удалил перезагрузку и изменил 1 * * * *, чтобы * / 1 * * * *, проблема решена! Куда мне отправлять респ птс марки? Спасибо!

Принятый ответ в этом Q & A также имел этот комментарий:

Мне кажется, Lubuntu не поддерживает синтаксис @Reboot Cron.

Дополнительные доказательства

В качестве дополнительного доказательства была эта тема, что кто-то пытался сделать то же самое и разочаровывался, что это не сработало Это называется: Тема: Cron — задания @reboot не работают .

Re: Cron — задания @reboot не работают

Цитата Сообщение от ceallred Посмотреть сообщение Это убивает меня . Попробовал скрипт оболочки. При запуске вручную создается файл журнала . перезагрузка, и задание не запускается или не создает файл журнала.

Системный журнал показывает, что CRON выполнил задание . но, опять же, нет вывода, и процесс не запущен. 15 июля, 20:07:45 RavenWing cron [1026]: (CRON) INFO (Запуск заданий @reboot) 15 июля, 20:07:45 RavenWing CRON [1053]: (ceallred) CMD (/ home / ceallred / Scripts / run_spideroak. sh> /home/ceallred/Scripts/SpiderOak.log 2> & 1 &)

Кажется, что cron не нравится команда @reboot . Есть еще идеи?

Хорошо . Частично решено. Я отмечу это как решенное и начну новую тему с новой проблемой .

Я думаю, что ответом было то, что мой зашифрованный домашний каталог не был смонтирован, когда CRON пытался запустить скрипт (хранится в / home / username / scripts). Перемещено в / usr / scripts, и задание выполняется должным образом.

Так что теперь это, кажется, проблема spideroak. Процесс запускается, но к тому моменту, когда процесс загрузки завершается, его уже нет. Я предполагаю сбой по какой-то причине . Новая тема, чтобы спросить об этом.

Как только этот пользователь выяснил свою проблему, он смог @reboot работать с записью crontab пользователя.

Я не совсем уверен, какая версия cron используется в Ubuntu, но, похоже, это указывает на то, что пользователь тоже может использовать эту версию @reboot или что ошибка была исправлена ​​в какой-то момент в последующих версиях cron.

Читайте также:  Как починить пластиковую фару

Я протестировал на CentOS 6 следующее, и это сработало.

пример

Затем я перезагрузил систему.

Убирайся

  1. Эта функция поддерживается как для системных, так и для пользовательских записей crontab.
  2. Вы должны убедиться, что он поддерживается / работает в вашем конкретном дистрибутиве и / или версии пакета cron.

Чтобы узнать больше о том, как работает настоящий механизм, @reboot я наткнулся на этот пост в блоге, в котором обсуждаются внутренности. Он называется: @reboot — объясняет простую магию крона .

Отладка crond

Вы можете увеличить детализацию crond , добавив следующее в этот файл конфигурации на дистрибутивах на основе RHEL / CentOS / Fedora.

Допустимые уровни: 0, 1 или 2. Чтобы вернуть этот файл к уровню ведения журнала по умолчанию, просто удалите его, «-L 2» когда закончите отладку ситуации.

Источник

@reboot is not working in CRON

I’m trying to run a shell-script and a command at the start of my Ubuntu server.

Here is my CRON

What I’m getting in the logs: grep CRON /var/log/syslog

My start.sh . It’s for launching an Unturned game server. I don’t think this script is important but I guess I should show you.

The thing is that if I execute ./check.sh from /home/steam It works fine. The bad news is that the @reboot doesn’t work for me when I reboot my VPS.

screen -list doesn’t throw anything if I reboot.

I’ve tried multiple things but didn’t work, the last thing I changed was adding -d parameter in the screen commands so the server wouldn’t need a terminal to write down the start-up.

I’m not sure how much can be done here to make @reboot work as expected.

How can I make my scripts run on boot? Are there any other alternatives to CRON ‘s @reboot ?

Thanks in advance.

3 Answers 3

Try man 5 crontab . If your crontab supported, you should see @reboot, @yearly, @monthly.

then try add some sleep for moment may can help.

Take a look at the systemd.service manpage. It describes how to configure systemd to manage a service. I am sure you will find examples for your system in /usr/lib/systemd/system or similar paths.

In your case, the service would look somewhat like this:

Источник

Не работает Cron. Перезагрузка сервера. Что я делаю не так?

На сервере установлен CentOS release 6.7 (Final). С Linux я сталкиваюсь впервые, познаний ноль. Все на уровне «гуголь» и логики. Поэтому, прошу совета:

Задача банальна: необходима перезагрузка сервера ежедневно в 07:00.

Сделано:
1. Создал скрипт по пути

Что пробовал:
1. Не смог разобраться, где посмотреть лог работы сервера, поставил ip на пинг на ночь. Пакетов потерянных не было, следовательно сервер не перезагружался.
2. Вручную запустил скрипт командой

  • Вопрос задан более трёх лет назад
  • 4967 просмотров

Добрый день. У вас опечатка в скрипте (shOutdown). Попробуйте:

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

Так же, в скрипте, вместо
shutdown -r now
прописал как у вас
shutdown -r 0

Все операции, который вы прописали, мне понятны.

Есть только 2 вопроса:
1. принципиально важно класть файл скрипта к юзеру в /home/username/ ?
2. когда я пытаюсь редактировать cron командой «crontab -e» — у меня перестает что-либо печататься в консоли. В комментарии скриншот приложить нельзя. Добавил в основную тему сверху

Источник

Thread: Cron — @reboot jobs not working

Thread Tools
Display

Cron — @reboot jobs not working

Still a Ubuntu newbie but usually am able to figure things out. This one has stumped me though.

Have a headless server running Lucid 64 bit. Everything is working great except for a couple of Cron jos I’m trying to have run at boot.

My user crontab looks like this:

Читайте также:  Не работает подсветка двери туарег

The SambaBkup script works like clockwork. The SpiderOak job doesn’t start. It works if I type the command in manually.

syslog only shows:

Yet ps -A doesn’t show a running SpiderOak process. It shows after starting manually.

Any help would be much appreciated.

Re: Cron — @reboot jobs not working

# m h dom mon dow command
01 * * * * /home/ceallred/Scripts/SambaBkup.sh

your cronentry says, run the script every hour first minute, so its
01:01 — 1am 1min , then
02:01 — 2am 1min , then
03:01 — 3am 1min

how you want it to run, do you want it to run every min or once at boot.

Re: Cron — @reboot jobs not working

Hi,
Is the job starting up & then erroring/exiting, or is it not being run at all? To find out try capturing output from the job in a logfile:
e.g. /usr/bin/SpiderOak.sh —headless > /path/to/logfile 2>&1 &

reboot & see what turns up in the logfile.

Re: Cron — @reboot jobs not working

Hi,
Is the job starting up & then erroring/exiting, or is it not being run at all? To find out try capturing output from the job in a logfile:
e.g. /usr/bin/SpiderOak.sh —headless > /path/to/logfile 2>&1 &

reboot & see what turns up in the logfile.

Still no luck. and no SpiderOak.log file was generated.

@sanjeevtrip. no problems with the SambaBkup job. It’s working as I like.

Re: Cron — @reboot jobs not working

Hi,
Its still unclear whether the job is being launched & failing without any output (spideroak problem), or not being launched at all (cron problem). My next suggestion to help narro down which would be to have the cron job run a wrapper script which DOES produce output (as well as launching spideroak), and again redirect the output to a log file. something like run_spideroak.sh

Re: Cron — @reboot jobs not working

Will try this when I get home from work tonight. Will post results

Re: Cron — @reboot jobs not working

This is killing me. Tried the wrapper script. Running manually generates the log file. rebooting and the job doesn’t run or create log file.

Syslog shows that CRON ran the job. but again, no output and the process isn’t running.

It’s seems like cron doesn’t like the @reboot command. Any other ideas?

Re: Cron — @reboot jobs not working

This is killing me. Tried the wrapper script. Running manually generates the log file. rebooting and the job doesn’t run or create log file.

Syslog shows that CRON ran the job. but again, no output and the process isn’t running.

Okay. Partially solved. I’ll mark this one as solved and start a new thread with the new issue.

I think the answer was my encrypted home directory wasn’t mounted when CRON was trying to run the script (stored in /home/username/scripts). Moved to /usr/scripts and the job runs as expected.

So now it appears to be a spideroak issue. Process starts, but by the time the boot process is finished, it’s gone. I’m guessing a crash for some reason. New thread to ask about that.

Источник

crontab’s @reboot only works for root?

man 5 crontab is pretty clear on how to use crontab to run a script on boot:

So I happily added a single line to my crontab (under my user account, not root):

But for some reason, myscript.sh wouldn’t run on machine reboot. (it runs fine if I invoke it from the command line, so it’s not a permissions problem)

What am I missing?

Update to answer @Anthon’s questions:

  1. Oracle-linux version: 5.8 (uname: 2.6.32-300.39.2.el5uek #1 SMP)
  2. Cron version: vixie-cron-4.1-81.el5.x86_64
  3. Yes, /home is a mounted partition. Looks like this is the problem. How do I workaround this?
  4. Currently, myscript.sh only echos a text message to a file in /home/me .
Читайте также:  Как настроить обработку петель

9 Answers 9

This can be a bit of a confusing topic because there are different implementations of cron. Also there were several bugs that broke this feature, and there are also some use cases where it simply won’t work, specifically if you do a shutdown/boot vs. a reboot.

One such bug in Debian is covered here, titled: cron: @reboot jobs are not run. This seems to have made it’s way into Ubuntu as well, which I can’t confirm directly.

Evidence of the bug in Ubuntu would seem to be confirmed here in this SO Q&A titled: @reboot cronjob not executing.

comment #1: . 3) your version of crond may not support @reboot are you using vix’s crond? . show results of crontab -l -u user

comment #2: . It might be a good idea to set it up as an init script instead of relying on a specific version of cron’s @reboot.

comment #3: . @MarkRoberts removed the reboot and modified the 1 * * * * , to */1 * * * * , problem is solved! Where do I send the rep pts Mark? Thank you!

The accepted answer in that Q&A also had this comment:

Seems to me Lubuntu doesn’t support the @Reboot Cron syntax.

Additional evidence

As additional evidence there was this thread that someone was attempting the very same thing and getting frustrated that it didn’t work. It’s titled: Thread: Cron — @reboot jobs not working.

Re: Cron — @reboot jobs not working

Quote Originally Posted by ceallred View Post This is killing me. Tried the wrapper script. Running manually generates the log file. rebooting and the job doesn’t run or create log file.

Syslog shows that CRON ran the job. but again, no output and the process isn’t running. Jul 15 20:07:45 RavenWing cron[1026]: (CRON) INFO (Running @reboot jobs) Jul 15 20:07:45 RavenWing CRON[1053]: (ceallred) CMD (/home/ceallred/Scripts/run_spideroak.sh > /home/ceallred/Scripts/SpiderOak.log 2>&1 &)

It’s seems like cron doesn’t like the @reboot command. Any other ideas?

Okay. Partially solved. I’ll mark this one as solved and start a new thread with the new issue.

I think the answer was my encrypted home directory wasn’t mounted when CRON was trying to run the script (stored in /home/username/scripts). Moved to /usr/scripts and the job runs as expected.

So now it appears to be a spideroak issue. Process starts, but by the time the boot process is finished, it’s gone. I’m guessing a crash for some reason. New thread to ask about that.

Thanks for all the help!

Once this above user figured out his issue he was able to get @reboot working out of the crontab entry of a user.

I’m not entirely sure what version of cron is used on Ubuntu, but this would seem to indicate that user’s can use @reboot too, or that the bug was fixed at some point in subsequent versions of cron.

I tested on CentOS 6 the following and it worked.

Example

I then rebooted the system.

After the reboot.

Take aways

  1. This feature does seem to be supported for both system and user crontab entries.
  2. You have to make sure that it’s supported/working in your particular distro and/or version of the cron package.

For more on how the actual mechanism works for @reboot I did come across this blog post which discusses the innards. It’s titled: @reboot — explaining simple cron magic.

Debugging crond

You can turn up the verbosity of crond by adding the following to this configuration file on RHEL/CentOS/Fedora based distros.

The valid levels are 0, 1, or 2. To revert this file back to it’s default logging level simply remove the «-L 2» when you’re done debugging the situation.

Источник

Оцените статью