Cron @daily ispmanager во сколько выполнится?
Привет всем. Подскажите, пожалуйста, во сколько выполнится скрипт, который я запланировал в cron через панель ispmanager. Там указал время выполнения @daily, а во сколько это?
- Вопрос задан более трёх лет назад
- 197 просмотров
Комментировать
Решения вопроса 1
Просто люблю качественно работать
Дейли прописан в конфиге и может быть любым я выставляю на два ночи всегда, если хотите конкретное время пропишите сами точное время когда хотите чтобы он запускался
Ответ написан более трёх лет назад
Комментировать
Нравится 1 Комментировать
Ответы на вопрос 0
Ваш ответ на вопрос
Войдите, чтобы написать ответ
- Linux
- +1 ещё
Не работает bin/bash в крон. Как решить?
- 1 подписчик
- 28 окт.
- 92 просмотра
When does `cron.daily` run?
When do entries in cron.daily (and .weekly and .hourly ) run, and is it configurable? I haven’t found a definitive answer to this, and am hoping there is one. I’m running RHEL5 and CentOS 4, but for other distros/platforms would be great, too.
14.6k 1 1 gold badge 47 47 silver badges 69 69 bronze badges
asked Apr 26, 2010 at 15:31
18.5k 23 23 gold badges 84 84 silver badges 135 135 bronze badges
On NetBSD, the times for the daily,weekly, monthly cronjobs are set in root’s crontab.
Nov 17, 2014 at 1:05
This question would be more useful if the question was edited to be more generic. At the very least make the question generic for any versions of redhat, centos distros instead of only for versions 4 and 5 (which are not widely used and are «end of production» (similar to end of life).
Jan 1, 2018 at 17:53
@TrevorBoydSmith — this question was asked nearly 8 years ago. Feel free to ask one updated for newer versions. But RHEL 6 didn’t even exist in April 2010: access.redhat.com/articles/3078#RHEL6
Jan 4, 2018 at 16:04
@warren my intent is not to criticize but just improve the question and stackoverflow in general. (i understand that RHEL 6 didn’t exist when the question was asked. because the question has soo many upvotes now it would be nice to have it more generic.)
Jan 4, 2018 at 16:16
@TrevorBoydSmith .. there is an answer for CentOS/RHEL 6 already 🙂 . I’d be happy to approve good edits from you if you have some ideas. Go ahead and make suggested edits to the question that you’ve thought of
Jan 4, 2018 at 18:13
10 Answers 10
For the distributions you mention:
On CentOS 5.4 (Should be same for RHEL5)
grep run-parts /etc/crontab 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly
So cron.daily runs at 04:02am.
Same on CentOS 4.8
answered Apr 26, 2010 at 16:23
Richard Holloway Richard Holloway
7,496 2 2 gold badges 25 25 silver badges 30 30 bronze badges
Is there any reason behind this? I can only assume it’d be the quietest time on the server.
May 13, 2010 at 14:55
@ what time it runs in ubuntu? can you please tell how i can check it? i am not able to understand the command output
Jan 2, 2016 at 11:16
@NarendraJaggi the «run-parts» command means «run everything in this folder». The cron.daily, etc. folders work because there is a cron job to execute run-parts on these directories. So grep run-parts /etc/crontab just finds the instructions on when run-parts is called for each of these directories.
Jan 21, 2016 at 15:57
This is no longer valid answer for CentOS 6 or higher, scroll down for more.
Oct 24, 2016 at 7:53
cant find it in /etc/crontab on CO 7
Sep 1, 2020 at 15:40
From the man page:
Cron also searches for /etc/anacrontab
/etc/anacrontab in my system (Fedora 12) :
1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
See also man anacrontab
answered Apr 26, 2010 at 15:35
2,128 17 17 silver badges 23 23 bronze badges
This is the case with CentOS 6 . Thanks.
Jul 22, 2013 at 15:59
That means 5am every «1» days?. Sorry, but this answers nothing.
May 13, 2016 at 16:50
@elysch Let me repeat the last line of my answer: See also «man anacrontab»
May 13, 2016 at 17:53
Good explanation of anacron here. Basically, anacron has no fixed start time, but rather will start the process based on when the last process ran, with a specified delay. If the machine is off when the process should have ran, then it will start the process when the machine comes back up, after the specified delay (barring no special ranges + random delay, see answer by @spechal ).
Jul 14, 2016 at 17:40
@mbrownnyc and also CentOS-7 too
Jan 1, 2018 at 17:30
For CentOS 6, you need to grep /etc/anacrontab and the answer varies if the server/laptop/dekstop/etc has been turned off or not.
cat /etc/anacrontab # /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=45 # the jobs will be started during the following hours only START_HOURS_RANGE=3-22 #period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
So, between the hours of 3AM and 10PM** (after reboot and after the machine has been up for 5 minutes^^), run /etc/cron.daily. If there is no reboot, the job should run at 3:05AM++.
** As defined by START_HOURS_RANGE ^^ As defined by FIELD_TWO (i.e. the 5 after the 1 in the cron.daily line) ++ plus a random time between 0 and 45 minutes as defined by RANDOM_DELAY
answered Oct 29, 2012 at 21:20
751 6 6 silver badges 10 10 bronze badges
For SuSE systems (specifically SLES 11.1 and openSuSE 10.3) the daily run time of the /etc/cron.daily scripts is controlled by the value of the DAILY_TIME variable set in the /etc/sysconfig/cron file.
If the DAILY_TIME variable is not set, it defaults to: (time of last boot + 15 minutes).
answered Aug 16, 2012 at 3:18
396 2 2 silver badges 7 7 bronze badges
thx a lot! SuSE is rather opaque to me and I appreciate your answer.
Aug 2, 2016 at 8:18
Same with OpenSUSE — and the default is «», ie. a quarter after the last boot. This approach is suitable for desktop computers, which tend to be turned off when not needed.
Dec 17, 2020 at 8:25
On Ubuntu, you’ll find a file /etc/crontab, from where this is configured. I guess it is something similar on RH and Centos.
answered Apr 26, 2010 at 15:33
99k 15 15 gold badges 180 180 silver badges 226 226 bronze badges
This is the right file for Ubuntu Lucid 10.04 LTS. My default setting is 6:25am for cron.daily.
Aug 8, 2011 at 13:46
Still set as 6:25 am on Ubuntu 15.04. But I notice that cron must insert some randomness in the time it starts the jobs. Looking at the timestamps of the files my daily job creates, I see on some days it runs as early as 6:26, and on others as late as 8:04 am.
May 6, 2015 at 10:51
Still set at 6:25am on Ubuntu 16.04 — Hourly at 17 minutes past hour. Daily at 6:25 am. Weekly at 6:47 am Saturday. Monthly at 6:52 am first day of month.
Mar 1, 2017 at 11:47
CentOS6.x/RedHat6.x installs by default the package cronie-anacron. You have to:
yum install cronie-noanacron
yum erase cronie-anacron
Then you now have /etc/cron.d/dailyjobs to configure the best schedule time for your daily, weekly and monthly jobs.
answered Aug 29, 2012 at 19:50
Daniel Santos Daniel Santos
77 1 1 silver badge 1 1 bronze badge
If anacron is installed, couldn’t you just edit /etc/anacrontab as per other comments here instead of uninstalling it?
Feb 21, 2013 at 20:18
@cincodenada That’s not what Daniel Stantos is suggesting.
May 14, 2013 at 16:28
I use Slackware (14.0), and did not have /etc/crontab . Also, anacron is not part of the distribution.
The solution on my system was as simple as running crontab -l as root:
root@flea:~# crontab -l # If you don't want the output of a cron job mailed to you, you have to direct # any output to /dev/null. We'll do this here since these jobs should run # properly on a newly installed system. If a script fails, run-parts will # mail a notice to root. # # Run the hourly, daily, weekly, and monthly cron jobs. # Jobs that need different timing may be entered into the crontab as before, # but most really don't need greater granularity than this. If the exact # times of the hourly, daily, weekly, and monthly cron jobs do not suit your # needs, feel free to adjust them. # # Run hourly cron jobs at 47 minutes after the hour: 47 * * * * /usr/bin/run-parts /etc/cron.hourly 1> /dev/null # # Run daily cron jobs at 4:40 every day: 40 4 * * * /usr/bin/run-parts /etc/cron.daily 1> /dev/null # # Run weekly cron jobs at 4:30 on the first day of the week: 30 4 * * 0 /usr/bin/run-parts /etc/cron.weekly 1> /dev/null # # Run monthly cron jobs at 4:20 on the first day of the month: 20 4 1 * * /usr/bin/run-parts /etc/cron.monthly 1> /dev/null
Настройка Cron
Системным администраторам, да и обычным пользователям часто приходится автоматизировать различные задачи по обслуживанию и работе с Linux с помощью скриптов. Это очень удобно, вы просто запускаете скрипт, и он делает все что необходимо без вашего вмешательства. Следующий шаг в этом пути — настроить автоматически запуск нужного скрипта в нужное время.
Именно для этих задач в Linux используется системный сервис cron. Это планировщик, который позволяет выполнять нужные вам скрипты раз в час, раз в день, неделю или месяц, а также в любое заданное вами время или через любой интервал. Программа часто используется даже другими службами операционной системы. В этой статье мы рассмотрим как выполняется настройка Cron и разберем основные часто используемые примеры.
Как работает Cron?
Фактически, Cron — это сервис, как и большинство других сервисов Linux, он запускается при старте системы и работает в фоновом режиме. Его основная задача выполнять нужные процессы в нужное время. Существует несколько конфигурационных файлов, из которых он берет информацию о том что и когда нужно выполнять. Сервис открывает файл /etc/crontab, в котором указаны все нужные данные. Часто, в современных дистрибутивах там прописан запуск утилиты run-parts, которая запускает нужные скрипты из следующих папок:
- /etc/cron.minutely — каждую минуту;
- /etc/cron.hourly — каждый час;
- /etc/cron.daily — каждый день;
- /etc/cron.weekly — каждую неделю;
- /etc/cron.monthly — каждый месяц.
В этих папках должны находиться скрипты, которые нужно выполнять с указанным интервалом. Скрипты должны иметь права на выполнение и их имя не должно содержать точки. Это очень сильно облегчает работу с планировщиком для новых пользователей. Также в файле crontab прописан запуск команды anacron, которая работает так же как и cron, только предназначена для задач, которые нужно выполнять раз в длительный период, например, раз в день, неделю, месяц, год.
Она позволяет выполнять их даже если компьютер работает не всегда и время от времени выключается. Дата выполнения задания последний раз записывается в файл /var/spool/anacron, а затем, при следующем запуске anacron проверяет был ли запущен нужный процесс в нужное время, и если нет, то запускает его. Сам же сервис cron больше рассчитан на выполнение задач в течение дня или с точно расписанным временем и датой.
Настройка Cron
Для настройки времени, даты и интервала когда нужно выполнять задание используется специальный синтаксис файла cron и специальная команда. Конечно, вы всегда можете отредактировать файл /etc/crontab, но этого делать не рекомендуется. Вместо этого, есть команда crontab:
Ее всегда желательно выполнять с опцией -e, тогда для редактирования правил будет использован ваш текстовый редактор по умолчанию. Команда открывает вам временный файл, в котором уже представлены все текущие правила cron и вы можете добавить новые. После завершения работы команды cron файл будет обработан и все правила будут добавлены в /var/spool/cron/crontabs/имя_пользователя причем добавленные процессы будут запускаться именно от того пользователя, от которого вы их добавляли.
Поэтому тут нужно быть аккуратным, и если вам нужно выполнять скрипты от рута, то и crontab нужно выполнить от рута, а не от пользователя. Это часто становится причиной проблем.
Синтаксис crontab
Как я уже говорил, время задается особым синтаксисом, давайте рассмотрим синтаксис настройки одной задачи cron:
минута час день месяц день_недели /путь/к/исполняемому/файлу
Нужно сказать, что обязательно нужно писать полный путь к команде, потому что для команд, запускаемых от имени cron переменная среды PATH будет отличаться, и сервис просто не сможет найти вашу команду. Это вторая самая распространенная причина проблем с Cron. Дата и время указываются с помощью цифр или символа ‘*’. Этот символ означает, что нужно выполнять каждый раз, если в первом поле — то каждую минуту и так далее. Ну а теперь перейдем к примерам.
Примеры настройки cron
Сначала можно посмотреть задачи cron для суперпользователя, для этого можно воспользоваться опцией -l:
Вы можете удалить все существующие задачи командой -r:
Давайте предположим, что нам нужно запускать от имени суперпользователя наш скрипт по адресу /usr/local/bin/serve. Какой-нибудь обслуживающий скрипт. Самый простой пример — запускать его каждую минуту:
Далее, усложним, будем запускать каждый час, в нулевую минуту:
Запускаем в нулевую минуту нулевого часа, каждый день, это в 12 ночи:
0 0 * * * /usr/local/bin/serve
Если идти так дальше, то можно запускать в первый день каждого месяца:
0 0 1 * * /usr/local/bin/serve
Можно в любой день, например, 15 числа:
0 0 15 * * /usr/local/bin/serve
В первый день недели первого месяца года, 0 часов 0 минут:
0 0 * 1 0 /usr/local/bin/serve
Или в нулевой день недели каждого месяца:
0 0 * * 0 /usr/local/bin/serve
Вы можете выбрать любую минуту, час и день недели, например, 15.30 во вторник:
30 15 * * 2 /usr/local/bin/serve
Понедельник считается первым днем, воскресенье — это седьмой или нулевой день. Еще можно писать сокращенное название дня недели, например sun — воскресенье:
30 15 * * sun /usr/local/bin/serve
Для того чтобы указать определенный интервал нужно использовать символ «-«, например, каждый час, с семи утра до семи вечера:
0 7-19 * * * /usr/local/bin/serve
Если нужно запустить команду несколько раз, можно использовать разделитель «,». Например, запустим скрипт в 5 и 35 минут пятого (16:05 и 16:35), каждый день:
5,35 16 * * * /usr/local/bin/serve
Вы можете захотеть не указывать отдельно время, а просто указать интервал, с которым нужно запускать скрипт, например, раз в 10 минут. Для этого используется разделитель косая черта — «/»:
Кроме того, для некоторых часто используемых наборов были придуманы переменные, вот они:
- @reboot — при загрузке, только один раз;
- @yearly, @annually — раз год;
- @monthly — раз в месяц;
- @weekly — раз в неделю;
- @daily, @midnight — каждый день;
- @hourly — каждый час.
Например, вот так просто будет выглядеть команда запуска скрипта раз в час:
Если же вы собрались добавить скрипт в одну из папок, то, как я уже говорил, нужно чтобы его имя было без точек и у него были права на выполнение:
sudo vi /etc/cron.daily/backup
#!/bin/bash
.
Скрипт должен выглядеть подобным образом. Теперь вы знаете как настроить cron, осталось проверить как все работает.
Отладка работы
После того как вы настроили правила, еще хотелось бы проверить работают ли они. Для этого ждем того времени, когда скрипт уже должен быть выполнен и смотрим лог cron. Иногда он находится в /var/log/cron, а иногда пишется в syslog. Например, у меня в crontab есть такая строка:
Она должна выполняться в 19.40 каждый день, теперь смотрим лог:
grep CRON /var/log/syslog
И видим что в нашем логе она действительно есть и выполняется целиком успешно. Если бы были какие-либо ошибки, то тут же было бы выведено сообщение.
Если нужно проверить скрипт, который находится в одной из специализированных папок, то тут еще проще, просто запустите run-paths, передав ей в параметр нужную папку или даже сам скрипт:
sudo run-parts /etc/cron.daily/
Дальше вы увидите весь вывод, включая вывод скрипта и сможете быстро понять в чем проблема.
Выводы
В этой статье мы рассмотрели как выполняется настройка cron для удобного планирования автоматических задач. Надеюсь, эта информация была полезной для вас.
Plans and pricing
All of our paid plans come with a no-quibble 30-day money-back guarantee — you’re billed monthly and you can cancel at any time. The minimum contract length is just one month. You get unrestricted Internet access from your applications, unlimited in-browser Python, Bash and database consoles, and full SSH access to your account. All accounts (including free ones) have screen-sharing with other PythonAnywhere accounts, and free SSL support (though you’ll need to get a certificate for your own domains).
$5 to $500/month
You can compare our plans in detail below.
What are «CPU seconds»?
With every PythonAnywhere account, you get a number of CPU-seconds included each day. This applies to all code run through our in-browser consoles, in your scheduled tasks and in your always-on tasks, but does not apply to your web apps.
A CPU-second is one second of full-power usage on a High Frequency Intel Xeon E5-2670 v2 (Ivy Bridge) Processor (one CPU core on an Amazon AWS m5.xlarge instance). Your code only uses up CPU seconds while it’s actually busy. If your code isn’t using any CPU power (maybe it’s not running, or it’s waiting for input or for a web request to return) then it’s not using any CPU seconds.
If you use up all of your included CPU seconds, don’t worry! You can always buy more — and even if you don’t, your processes will still run, in the tarpit.
Tarpitted processes run at a lower priority than users who haven’t hit their limit yet, but they get any spare capacity that we have on our server cluster, unless they’re using gigabytes of RAM.
What do we mean by a «typical» website? Why don’t we just guarantee a certain number of hits/day capacity?
We guarantee a certain amount of computing capacity for your web app, but how many hits/day you can get out of that depends on you. If you write a website that does tons of calculations for every request then you won’t be able to handle as many hits per day as our estimate. If you write a super-efficient one using a lightweight framework, you’ll be able to handle more.
Our estimates are based on real-world websites that we host, like web2py.com, so we’re confident that they’re a good indicator of what a typical website will be able to handle.
How it works, under the hood
The web app compute capacity is defined by the number of web workers associated with your app. Each web worker is an independent process capable of serving up your entire app, so if you have more than one, while one is busy handling one request another can take over. If you only have one worker (or if all of your workers are busy) then requests are queued up and served when a worker becomes available.
For sites without a lot of traffic — even if they have a lot of users accessing pages occasionally — one web worker is enough. But when things get busy, if two people happen to hit your app at exactly the same time, it’s useful to have more than one.
Making things faster with static files
Static files (that is, stuff that doesn’t change frequently and that you store in simple files on the disk, rather than creating dynamically with your Python code — like CSS files or JavaScript) can be configured to be served separately, without tying up your web workers, using the «Static files» section of the web app configuration page.