Имеем Windows Server 2012 R2. Задача — автоматически перезагружать сервер каждый понедельник в 5 утра. Приступаем.
Запускаем Планировщик заданий, создаём в нём папку «reboot»:
Делаем Create Basic Task… Запускается мастер:
Указываем Name, Description:
Кликаем Next:
Выбираем период Weekly. Next:
Указываем начало — ближайший понедельник 5 утра. Ставим галку Monday. Next:
Выбираем Start a program. Next:
В Program/script: пишем:
%SYSTEMROOT%\System32\shutdown.exe
В Add arguments (optional):
/r /f /t 90 /d p:0:0 /c "Перезапуск по понедельникам. Отмена: shutdown.exe /a"
Где:
- /r — перезагрузка,
- /f — принудительное закрытие всех приложений,
- /t 90 — время ожидания до начала перезагрузки 90 сек,
- /d p:0:0 — причины перезагрузки для журнала. В данном случае, мы указали: p — запланированная перезагрузка, 0:0 — «Other (planned)»,
- /c комментарий в свободной форме длинной не более 512 символов. Комментарий будет показываться юзерам 90 секунд. За это время можно отменить перезагрузку командой shutdown.exe /a.
Список параметров и причин перезагрузки можно посмотреть shutdown.exe /?
Мастер не доделали, кликаем Finish. Создаётся задача — редактируем её.
Ставим Run whether user is logged on or not. Добавим галку Run with highest privileges. Ok:
Нас попросят ввести имя пользователя, от имени которого будет выполняться задание. И пароль. Готово:
Сам пока не проверял результатов. В ближайший понедельник посмотрим…
P.S.
Две недели прошло — шедулер нормально перезагружает сервер по понедельникам.
This article has detailed steps to schedule a restart of your Windows VPS Machine 2008/2012/2016. This can be achieved by just adding a task at task scheduler of your Windows Server Machine.
- Login into your Window server remote desktop.
- Open Run prompt, type taskschd.msc, and click ok.
3. Now Go to Action >> Create task.
4. set the name of your task and select the operating system of your windows vps from drop-down.
Please remember to check the following option :
a. Run whether user is logged on or not
b. Run with highest privileges
5. Now Go to Trigger tab and schedule the time of reboot. (by clicking on New…) in this stage, you can define the time you want to schedule a reboot. (weekly, daily, or monthly)
6. Now set the reboot action with adding command C:\Windows\System32\shutdown.exe with add argument /r and click ok. (by clicking on Action Tab)
That’s all. This machine (VPS , VM and other ..) is now set to reboot every weekend.
Regularly rebooting your computer on a weekly or periodic basis can enhance performance by clearing temporary files, flushing RAM, and closing unnecessary applications. Additionally, a reboot can improve reliability by ensuring that the system is working with its most available resources, free from any unwanted running applications. In this article, you will learn how to schedule a reboot of the Windows Server.
Creating a reboot schedule via Task Scheduler
In our previous article, we covered the process of creating automated tasks using Task Scheduler on Windows. In this article, we will continue to utilize Task Scheduler and demonstrate how to schedule a reboot of a Windows server. You can set up reboot schedules that occur daily, weekly, monthly, or at a specific time and date.
1. To start off, log in to the Windows Server. Then search for the task scheduler in the Windows search and open it.
2. Then under Actions on the right-hand side, click Create Task.
3. Next, we will need to configure the following options:
a) Name the New Task.
b) Check the option Run with the highest privileges.
c) Select the operating system, and select the OS of your VPS, from Configure For dropdown list.
d) Optional: Run whether user is logged on or not this will allow the task to run even when the user is not logged on/connected.
4. Then, navigate to the Triggers tab and click New in the bottom left corner.
5. Next, on the New Trigger window you will be able to set a schedule for the reboot. In this guide, we will be creating a Weekly trigger every Sunday. Once you’ve configured your trigger to your preferences, click OK to save the trigger.
6. You will then see the trigger created on the Triggers tab, as seen below. Then navigate to the Actions tab.
7. On the Actions tab, click New in the bottom left corner.
8. On the New Action window, for Action select Start a program. Then for Program/script click Browse and locate C:WindowsSystem32shutdown.exe, and for the Add arguments text field enter /r. Now, click OK to save the action configuration.
9. Finally, click on OK to save this configuration.
10. To verify that your task has been created, on the Task Scheduler window click Task Scheduler Library on the left menu. You will then see your created task in the middle of the window. You have successfully configured the scheduled reboot for Windows Server.
Перезагрузка сервера через командную строку и планировщик задач
Иногда сервера необходимо перезагружать, например, для установки обновлений. В рабочее время, зачастую, сделать это не возможно по причине того, что пользователи работают с сервером и прерывать их работу не вариант. Конечно, можно или задержаться на работе или прийти раньше для выполнения перезагрузки… Но гораздо проще и удобнее запланировать перезагрузку через диспетчер задач.
Для начала рассмотрим, как перезагрузить (или выключить) систему через командную строку. В этом нам поможет утилита shutdown.exe. Не будем рассматривать все возможные параметры использования, их можно посмотреть запустив программу из консоли с параметром /? или просто без параметра, рассмотрим набор параметров, который использую я.
shutdown.exe /r /f /t 90 /d p:2:16 /c "Перезапуск для установки обновлений"
в данном случае:
/r — перезагрузка сервера
/f — принудительное закрытие всех приложений.
/t 90 — время ожидания до начала перезагрузки 90 сек.
/d p:2:16 — указание причины перезагрузки, которая отобразиться в системном журнале. В данном случае, мы указали:
p — запланированная перезагрузка, 2:16 — «Операционная система: Установка пакета обновления (Запланировано)»
/c «Перезапуск для установки обновлений» — комментарий в свободной форме длинной не более 512 символов.
Итак, после выполнения данной строки на экране появится окно с указанным нами комментарием.
Пока идет указанное нами время ожидания, есть возможность прервать запуск перезагрузки в случае необходимости выполнив shutdown.exe /a в командной строке.
После окончания времени ожидания станция будет перезагружена. При этом в системный журнал попадет запись о перезагрузке, ее причинах и нашим комментарием.
Таким образом, если за серверами следят несколько Администраторов, у них не будет вопросов почему сервер перезагружался.
Для того чтобы запланировать перезагрузку, разумно использовать планировщик задач. Не буду здесь описывать как создавать в нем задачи, отмечу только, что параметры командной строки следует вынести в соответствующую строчку, как на скриншоте
Обратите внимание, что путь я преобразовал через системную переменную:
%SYSTEMROOT%\System32\shutdown.exe
Таким образом, не важно на какой диск установлена система, программа запустится.
Созданную задачу можно устанавливать на определенные дату/время с повторением или без по вашему желанию. Система будет перезагружена в назначенное время и в системном журнале останется соответствующая запись.
Разумеется, вы можете экспортировать созданную задачу в xml-файл и использовать как шаблон при создании подобной задачи на другом сервере вашей сети.
Следует также отметить, что таким же образом можно перезагрузить (или выключить) удаленный компьютер, если использовать параметр /m \\ИМЯ_КОМПЬЮТЕРА.
Утилита Shutdown имеет и оконный интерфейс, для этого утилиту следует запустить с ключом /i
Данный диалог позволяет выполнить перезагрузку на компьютерах сети (AD) без использования командной строки.
Статьи в тему:
Shutdown (technet)
Перезагрузка или завершение работы удаленного компьютера и документирование причины
(Visited 5 203 times, 1 visits today)
Posted by Rewalon
If you are looking for the good old AT command on Windows 8, Windows Server 2012 or newer OS, you will notice that the command has been deprecated. Instead you should check out the schtasks.exe command line tool, that also is a pretty powerful tool.
The need for scheduling a server reboot
There can be many reasons why you will need to schedule a restart of a server instead of just rebooting it right away. Most of the time it is because it is being used and you have to wait for a maintenance windows to perform the task. Often I have needed to schedule a server reboot or a Windows Service restart and I have been using the good old AT command for this task in many years. However, in newer OS starting with Windows 8/Windows Server 2012 the AT command is not working anymore. The new command to do those kind of tasks now, is the schtasks.exe command line tool. If you try to run the AT command on a newer operating systems, you will get the message below:
How to schedule a server restart with schtasks.exe
Ok, let’s have a look on the schtasks command. To schedule a server restart you should run the following command line:
schtasks /create /sc once /tn Reboot /tr “shutdown – r -f “”restart””” /st 22:00
This command will create a scheduled task that will run once at 22:00 and execute a forced reboot of the server/computer you have created the task on. If you prefer to use the graphic user interface to check up on your newly created task or to change the time it will run, you can use the Windows Task scheduler. You can of cause also remove a task with schtasks, like in the example below:
schtasks /delete /TN “reboot”
The smart thing about scripting this command instead of using the Task scheduler GUI is that you can run other command line tools first and then finish with a server reboot then the task is done, but you can of cause also use the Task Scheduler GUI if you are more comfortable using that.
Final thoughts
I hope you found what you were looking for in this post. If you have any questions, please drop me a comment below.