- how can I schedule a reboot in Linux?
- 6 Answers 6
- How to Schedule Reboot Daily in Linux
- How to Schedule Reboot Daily using Crontab
- Conclusion
- About the author
- Syeda Wardah Batool
- Как запланировать перезагрузку в Linux?
- Перезагрузите систему с помощью терминала
- Как запланировать перезагрузку в Linux
- Заключение
- Daily server reboot cron?
- 2 Answers 2
how can I schedule a reboot in Linux?
I’m sorry for the noob question. Pls help me. Thanks.
The real question is why you’d want to be doing this regularly, do you have a leaky application or something? If you’re scheduling regular reboots to solve a problem then you’ve probably got a bigger problem.
I’m not voting down, because it’s sort of a policy decision (and I think nightly reboots are a bit excessive), but regularly scheduling reboots across an infrastructure are a decent way of ensuring that machines have up to date kernels and all services running are patched. I’ve heard a 3 month uptime limit as being a good middle ground.
If this was a comment on the question, rather than an answer, I would upvote it. Actually I would change my mind, because the question was ambiguous about whether this was a one-time or regular thing. 🙂
/etc/crontab entry like 30 23 15-21 * 6 /sbin/shutdown -r now will reboot at 23:30 on the 3rd Saturday of every month.
6 Answers 6
Type shutdown -r 0:00 and it will reboot at midnight.
If you want to reboot each night, add a cron entry using crontab -e as root to run shutdown -r each midnight
Oups yes sorry, I misread Tobu comment and think he tells 0:00 was useless in the first command. I edited to correct (and Massimo answers too)
Note that issuing shutdown -r 22:00 then closing the terminal will cancel the reboot command. nohup shutdown -r 22:00 & for maintaining the reboot command after closing the terminal window.
Another option is the at command, available on many Linux distributions. See the man page for more info, but the general syntax for your purpose would be:
To quote the OS X man page:
at — executes commands at a specified time
Sound like what we’re talking about. 😉
Adding this entry to /etc/crontab should do:
0 0 * * * /sbin/shutdown -r now
The original question made it sound like he wanted it rebooted every night. He actually wants it rebooted every 3rd Saturday, which would still be easiest with a crontab
i dont know what’s wrong but i cannot find the crontab. what i have is the cron.d;cron.daily; cron.weekly; cron.monthly; I’m sorry for the noob question.Pls help me. thanks
It depends on the distribution you’re using, but usually you should find a file called «crontab» in your system’s /etc directory. You should also be able to examine the current crontab using the command «crontab -l», and to edit it using «crontab -e».
As far as I know, you cannot use cron to schedule tasks for «last Friday of each month» or «third Thursday in each month». What you can do, however ugly it seems, is to have a script run every Saturday at 23:30 and then have this script determine if this particular Saturday is the third Saturday of the week (can be done using date and maybe cal commands).
I hope this helps. I have not found an elagant solution to this problem. I found this thread, because I was searching for a solution for the same problem.
the comments above of «30 23 15-21 * 6 /sbin/shutdown -r now» will work. It’ll basically only run on the third week of the month, but only when it’s also saturday
I created the following two lines: «30 23 1-7 * 4 date» and «30 23 1-7 * 3 date». I got two mails last night both saying: «Wed Mar 7 23:30:02 CET 2012»
the last field matches the day of the week, with zero being sunday. the 4 cronjob should not have matched on a wednesday.
That is what I meant. The rule you wrote do not mean what you think it means. It will trigger the job every day for a week. No matter the weekday.
1) at the command line type which reboot
2) once you know where reboot is located (usually /sbin/reboot) cd into one of the the directories in /etc/cron.daily , /etc/cron.weekly , /etc/cron.hourly etc. ie cd /etc/cron.weekly
3) create a file (using nano or vim) call it zzreboot and add the following lines:
The reason you want to call the file zzwhatever is to make sure it’s the last job called after all other jobs. To make sure just do an ls -l in the directory and verify it’s the last file.
How to Schedule Reboot Daily in Linux
Reboot the system means turning off all the applications of the device and restart with a new state. We need to reboot when the system crashes and fails to work correctly. Whenever the system restarts, it comes with a fresh copy of the software and is loaded into the memory.
For Linux users, it is always easy to find the solution of operations you’re confused about. Similarly, if you want to reboot the system, you don’t need to install any specific tool or package.
Some of the processes also require rebooting the system for the configurational changes. It is good to reboot the system when needed, but doing it daily could create problems. So be careful!
The Crontab, or we can call cron table, is the built-in Linux utility that helps to schedule the processes and execute them at the specified time. The Cron table consists of predefined scripts and commands from where the Cron daemon reads them. The Cron allows the user to configure the predefined commands in the Cron table and set them to run automatically.
Some tasks need to perform daily, while some weekly, and similarly monthly and yearly.
Follow the guide if you want to schedule a reboot daily on the system:
How to Schedule Reboot Daily using Crontab
Following is the format of Crontab:
Fields | Allowed Value |
---|---|
MIN (minutes) | 0 – 59 |
HOUR (hour field) | 0 – 23 |
DOM (day of month) | 1 – 31 |
MON (month field) | 1 – 12 |
DOW (day of the week) | 0 – 6 |
CMD (command) | Command to be executed |
Open a terminal and type the mentioned command to get /etc/crontab file:
The file will look like this:
You can also get it using the command:
(You will be asked to select a preferable editor such as vim, nano, etc. for crontab file)
Scroll down the file and write the mentioned line at the end of it:
The above line will force the system to restart daily at 10 a.m.
Note that: The shutdown –r command is used to restart the system.
Conclusion
The writeup has shown how to reboot the system daily. You can do it by typing the shutdown -r command regularly on the terminal. However, to avoid writing the shutdown command daily, you can do it through Crontab.
The Crontab utility helps to schedule processes and execute them on time. All the predefined commands are written in the Cron table from where Cron daemon reads them. To schedule a process, you can edit the /etc/crontab file and set timings according to the requirement.
About the author
Syeda Wardah Batool
I am a Software Engineer Graduate and Self Motivated Linux writer. I also love to read latest Linux books. Moreover, in my free time, i love to read books on Personal development.
Как запланировать перезагрузку в Linux?
Здравствуйте, друзья. В этой статье вы узнаете, как запланировать перезагрузку в Linux. Эта статья также поможет новичкам освоить Crontab и использовать его для более сложных задач.
Запланировать перезагрузку может показаться довольно простой задачей, но иногда она может ввести в ступор не опытного пользователя. К счастью, для нас существует Crontab и с ним этот процесс проще, чем вы думаете.
Ведь благодаря Crontab вы можете выбрать точное время и частоту выполнения задачи.
Перезагрузите систему с помощью терминала
Первое, что нам нужно знать, то это как перезагрузить систему с помощью терминала. Для этого существует несколько команд и опций, но в целом вы можете использовать команду reboot и команду shutdown с опцией -r.
В качестве примера можно привести следующее. Если вы хотите перезагрузить компьютер с помощью команды reboot, запустите терминал и введите команду.
Если вы работаете от пользователя root, то будет достаточно следующего.
Но если вы хотите использовать перезагрузку, которая является более гибкой, то используйте эту команду.
Как видите перезагрузить машину с помощью терминала очень просто. Теперь давайте сделаем это с помощью crontab.
Как запланировать перезагрузку в Linux
Crontab — это простой текстовый файл, хранящий список команд, которые должны быть выполнены в указанное пользователем время.
Таким образом, благодаря Crontab вы можете запланировать перезагрузку каждый раз, когда захотите. Это действительно просто.
Сначала откройте терминал и выполните следующую команду.
Как только вы введете пароль пользователя, вам будет предложено выбрать текстовый редактор для редактирования файла. В данном случае я выберу nano, потому что он самый простой в использовании.
Далее вам будет представлен файл, о котором идет речь, чтобы вы могли установить, как часто перезагружать компьютер.
Все дело в команде, которую вы собираетесь задать. Например, если вы хотите запланировать ежедневную перезагрузку в 04:00, добавьте в файл следующее.
0 — минуты
4 — час
* — день месяца
* — месяц
* — день недели
/sbin/shutdown -r -это команда перезагрузки
Итак, приведенная выше команда указывает, что каждый день недели, каждый месяц в 4:00 будет выполняться команда /sbin/shutdown -r , которая перезагрузит систему.
Crontab очень гибок, поэтому вы можете изменять время и частоту. Например, если вы хотите, чтобы компьютер или сервер перезагружался только по воскресеньям в это 4 утра.
Когда код будет готов, выйдите из редактора, нажав Ctrl + x нажмите Y для сохранения изменений и enter для выхода из редактора.
Теперь ваш компьютер или сервер будет перезагружаться автоматически каждое воскресенье в 4 утра.
Заключение
В этой простой заметке вы узнали, как запланировать автоматическую перезагрузку в Linux с помощью Crontab. Таким образом вы можете указать когда вам нужна перезагрузка для обслуживания ПК или сервера.
Daily server reboot cron?
I want to create a cron job which executes daiy at assigned time and it restart the ubuntu server. I try to add reboot only in cron, but it is not working, whereas it works when I try to execute it from CLI. Please advise, what command should I add in cron, so that it reboot the server daily at specific time.
May I ask why you need to reboot a server on a daily basis? This is an indication to me you’re doing things wrong. Probably.
@gertvdijk i’ve run into situations where you need to reboot a machine regularly. Proprietary software that gets a bad memory leak after ~30 hours of uptime, things like that.
If the problem is that some application is leaking memory over time, a better solution wold be to just restart that application service.
2 Answers 2
You need to run the following command:
with root pirviliges. The way to do it is to use root’s crontab, not your user crontab. A sudo before the usual crontab command does that:
Tip: You can switch the shell’s standard editor for things like crontab and visudo with sudo update-alternatives —config editor and then select the editor of your choice.
Editing the crontab you should add the following line to your file:
# For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command @daily root /sbin/shutdown -r now
One has to remove «root» if you edited with the command: sudo crontab -e.
The «@daily» here is a shortcut for every day at midnight (equivalent to «0 0 * * *»). By the way — why do you want a daily reboot?
EDIT — see https://help.ubuntu.com/community/CronHowto for the following: «Crontab commands are generally stored in the crontab file belonging to your user account (and executed with your user’s level of permissions). If you want to regularly run a command requiring administrative permissions, edit the root crontab file: sudo crontab -e»
EDIT — thanks to @charlesbridge for his comment — edited answer to include the full path