I want to restart some specific service for a specific time every week. Can I use the NET command?
— Shanmuga
Hi Shanmuga.
Yes. With the help of the Windows Task Scheduler, you can use the NET command to restart a specific service at a specific time.
To do so:
1. Find the name of your service
Each Windows Service has two names — a short service name and a friendly display name. We need the service name for the NET command.
If you don’t already know the service name, or want to validate it:
-
Launch the Windows Services application. You can find it by searching for “services” in the Control Panel, or by running services.msc at a command prompt.
- Scroll to locate your service in the list:
-
Double-click the entry to open the service’s properties. The service name is displayed at the top.
Here we see that the name of the Print Spooler service is actually “Spooler”:
2. Create a batch file to restart your service
With the service name in hand, we can now use the NET command to restart the service.
Create a new batch file and enter the following two commands:
NET STOP «Your Service Name«
NET START «Your Service Name«
Please replace Your Service Name with the service name identified in step 1. The quotes are required if the service name contains a space.
For example, if your service name is “Spooler”, the batch file should look like this:
NET STOP «Spooler»
NET START «Spooler»
Save the batch file to a well-known location. We’ll use it in the next step.
Test the batch file
At this point, we recommend performing a quick test to ensure that the batch file works as expected. Run it from an administrative command prompt and confirm that it restarts your service.
3. Create a scheduled task to run the batch file at the time you wish to restart the service
Now that you are able to restart the service with the batch file, let’s schedule it to run whenever you like.
For example, here is how we would restart the Print Spooler service every Sunday at 1 AM:
-
Open the Windows Task Scheduler. You start it from the Control Panel or by running taskschd.msc from a command prompt.
-
Click Create Basic Task on the right:
The Create Basic Task Wizard window will come up.
-
Give the task a descriptive name:
Click Next to continue.
-
Select Weekly and click Next:
-
Set the day and time to restart the service:
Click Next to continue.
-
Ensure that the action is Start a program and move to the next step:
-
Enter the full path to the batch file you created to restart the service:
Click Next to continue.
-
Review the summary and make sure that everything looks good.
Check the Open the Properties dialog… box at the bottom because we’ll need to adjust one of the tasks properties:
Click Finish.
-
And finally, in the Properties window, check the Run with highest privileges box. The batch file must run with administrative rights so that it can restart the service.
Click OK to save your settings.
Going forward, the new task will come alive at the scheduled time to promptly restart the service. You should be good to go.
Improvement: Use ServicePilot instead of NET for better reliability
While NET.EXE will work for most situations, there are a few scenarios where it may fall short.
Does your service:
- take longer than 30 seconds to shut down?
- occasionally hang and refuse to stop?
If so, the NET STOP command may fail. And when that happens, the subsequent call to NET START will fail too (because the service will not be idle). The end result is that your service will be left in an unusable/unresponsive state!
Our free ServicePilot utility was built to work around NET’s shortcomings. It will wait for longer than 30 seconds if necessary and will do its best to forcibly terminate an unresponsive service.
To use ServicePilot instead of NET:
-
Download ServicePilot from our website. Save the executable in a well-known location (e.g. C:\Apps\ServicePilot\ServicePilot.exe).
-
Edit the batch file you created to restart the service.
-
Delete the two NET lines.
-
Add the following line (adjusting the full path to ServicePilot and your service name as necessary):
C:\Apps\ServicePilot\ServicePilot.exe -restart -wait 300 «Your Service Name«
Note: The -wait 300 parameter instructs ServicePilot to wait up to 300 seconds (5 minutes) for the service to stop and restart. Feel free to increase (or decrease) the timeout based your specific use case.
-
Save the batch file.
As you did with the NET version, please perform a quick test to ensure that the updated batch file works as expected. Launch it from an administrative command prompt and confirm that it restarts your service.
Best of luck with your service!
UPDATE: Use our free Service Scheduler utility instead of the Task Scheduler
We got tired of manually creating batch files and scheduled tasks to control our services so we created a free application to do it all. 🙂
With Service Scheduler, you can easily start, stop or restart any Windows Service — daily, weekly or monthly at a time of your choosing:
Service Scheduler is completely free and super easy to use. You can schedule your service in seconds:
Download Service Scheduler and check it out today!
You may also like…
In today’s digital world, keeping your Windows Server safe and running well is key. One big part of this is making sure to restart it regularly. But how do you do this the right way on a Windows Server? Is there a simple method that lets you automate and tweak this process?
Enter the Windows Server 2022 Task Scheduler. This tool is a game-changer, bringing lots of new abilities to the table. It lets you set up tasks to run when you want, react to certain events, and trigger tasks based on set times or events. You’ll find it’s really flexible and can do a lot for you!
I’m here to show you how to make the most of the Task Scheduler for scheduling restarts on your Windows Server 2022. I’ll walk you through everything – from starting out to handling any problems you might run into. Let’s dive in and make your server work even better!
Key Takeaways:
- The Windows Server 2022 Task Scheduler offers advanced features to automate and schedule tasks on your server.
- Scheduling regular restarts is crucial for maintaining server performance and security.
- The Task Scheduler allows for customization, offering triggers based on specific times, dates, recurring schedules, or system events.
- In the upcoming sections, we’ll explore the step-by-step process of scheduling restarts on Windows Server 2022 and delve into troubleshooting and optimization tips.
- Stay ahead in server management with the power of the Task Scheduler!
Using Task Scheduler to Schedule Restart on Windows Server 2022
It’s key to regularly restart your Windows Server for best performance. The Task Scheduler in Windows Server 2022 makes it simple to do. Just a few steps and you’re set with automated restarts.
Here’s a step-by-step guide for setting restarts on Windows Server 2022:
- Start by opening Task Scheduler. You can find it by searching in the Windows search bar.
- Create a new folder in the Task Scheduler Library by right-clicking. This step helps keep your tasks organized.
- Now, inside the new folder, right-click and choose “Create Task.”
- Give your task a name and a description.
- Adjust the settings to “Run whether the user is logged on or not” and “Run with highest privileges” for a smooth operation.
- Pick when you want the restart to happen.
- Choose the “shutdown” action and set the arguments to “-r -t 60”. This setting restarts the server in 60 seconds.
- Set other conditions or settings that you might need.
- Finally, save this task. It’s now ready to restart your server at the chosen time.
Scheduling restarts keeps your server fast and avoids problems. It means you don’t have to manually restart, and your server restarts when it’s best.
Always avoid restarting during crucial tasks. It could make them fail. So, choose your restart times carefully to not disturb anything else.
Using Task Scheduler in Windows Server 2022 makes managing your server easier. It helps keep everything running smoothly.
Next, we’ll look at how to schedule regular backups in Windows Server 2022. Backups are crucial for protecting your data and quick recovery after a disaster.
Keep reading: [H2] Scheduling a Weekly Backup on Windows Server 2022.
Scheduling a Weekly Backup on Windows Server 2022
Setting up regular backups is crucial on Windows Server 2022. Not only should you schedule restarts, but also back up your important data weekly. AOMEI Backupper Server is a great tool for this. It lets you back up your system, disks, partitions, and files efficiently.
AOMEI Backupper Server helps you make a backup plan that fits your needs. Weekly backups strike a good balance, protecting your data without using up too much space. This way, you reduce the chances of losing data for long. Setting backups to run every week also makes the whole process smoother and less prone to mistakes.
AOMEI Cyber Backup also shines for managing backups centrally on Windows servers. It lets you set up backups to happen daily, weekly, or monthly. This gives you a dependable routine for your backups.
When you set up backups, think about how much storage space you need. Using external drives that have more than enough space is wise. This guarantees room for many backups and any data you add later.
Choosing the right backup target drives is critical. Make sure they don’t have certain server folders or a special system partition. Including these could mess up your backup.
If a backup fails because the target drive doesn’t have enough space, you might need to fix the drive letter issue. Use a tool in Windows Server Essentials to do this. Then, your backups can run smoothly again.
With AOMEI tools, you get to decide what to back up. You can back up everything or just specific parts. This is great for focusing on what’s most important.
By using good backup software regularly, like AOMEI Backupper Server or AOMEI Cyber Backup, your data stays safe on Windows Server 2022.
About Windows Server 2022 Task Scheduler
Windows Server 2022 Task Scheduler lets users set up and automate tasks on their servers. It’s much better than past versions, making scheduling tasks easier and more reliable.
It has lots of ways to start tasks. You can choose specific start times, set tasks to repeat daily or weekly, or start them when certain events happen on the server.
The Task Scheduler also does actions automatically. Users can make it run scripts, send emails, or do other tasks without someone pressing a button.
This tool gives you lots of control over your tasks. You can say they should only run in certain computer states, like when the power’s on or the internet’s working. This helps make sure your server runs at its best.
Windows Server 2022 Task Scheduler got better with new updates. Now, tasks can start based on specific events. This makes your schedule more flexible and reactive.
It also works great with PowerShell, which is a powerful scripting tool. You can use PowerShell to make your tasks do almost anything, adding a lot of flexibility.
There’s also better logging to help you see what your tasks are doing. This makes it easier to fix problems and keep everything running smoothly.
And it doesn’t stop there. Windows Server 2022 Task Scheduler works with Windows Admin Center. This makes it simpler to manage tasks on several servers and keeps them safe.
So, the Windows Server 2022 Task Scheduler gives you lots of ways to schedule and run tasks. It’s reliable, fast, secure, and easy to use. It’s a great way to handle tasks on Windows Server 2022.
Troubleshooting Tasks in Windows Server 2022 Task Scheduler
Having trouble with tasks in Windows Server 2022 Task Scheduler not running correctly? It’s important to find and fix the problem. By checking the Task Scheduler, you can pinpoint what’s wrong and get things working right again. Here’s how you can troubleshoot:
- Check Task History and Logs: Look at the task history and logs in Task Scheduler. You might find error messages or odd behavior. These clues can show why tasks don’t work as they should.
- Verify Task Settings, Triggers, Actions, and Conditions: Make sure all the task settings are correct. This includes triggers, actions, and conditions. They need to match what you expect the tasks to do.
- Ensure Proper User Account Permissions: Check if the user running the tasks has enough permissions. Not having the right permissions can stop tasks from working.
- Test Tasks Manually: Run the tasks by yourself. This is outside of the Task Scheduler. It can show if the tasks have a problem or if it’s the Task Scheduler setup.
- Utilize Tools like Event Viewer or PowerShell: Use tools like Event Viewer and PowerShell to get more info. They show more details about why tasks might fail. This can help you fix the problem.
- Enable Additional Logging and Debugging Options: Turn on detailed logging in the Task Scheduler. This shows more about how tasks run. It may reveal hidden errors.
Always remember to keep track of the changes you make while troubleshooting. And test each change one at a time. This way, you can clearly see what fixes the issue.
If problems continue, asking for help from the Windows Server community might be smart. They offer many tips and personal experiences on Windows Server community forum.
By using these steps and listening to others’ advice, you can solve issues in Windows Server 2022 Task Scheduler. Good luck!
Automating Task Management in Windows Server 2022 Task Scheduler
Windows Server 2022 Task Scheduler is a tool for automating tasks, scripts, and programs. It saves time and makes tasks more reliable. You can schedule tasks to run at set times, intervals, or when certain events happen.
The Task Scheduler has many trigger options for different needs. You can set tasks to run on certain dates, regularly, or when an event occurs. This lets you decide when tasks happen.
It also allows for advanced actions to make tasks better. For instance, tasks can include running scripts, sending email updates, or making system restore points. These features offer more control over how tasks are completed.
You can add conditions for tasks to follow. For example, make a task run only on certain networks or power statuses. This lets you customize task timing based on your needs.
Task automation is very helpful, like for scheduling a server restart. With the Task Scheduler, users can set specific restart options. You can use commands like “shutdown -r -t 60” to restart after a 60-second delay.
Add backup software to the Task Scheduler for regular backups. AOMEI Backupper Server and AOMEI Cyber Backup work well. They have many backup features and work with the Task Scheduler to automate backups.
PowerShell is great for managing tasks in Task Scheduler. It lets you set up and control tasks easily. PowerShell is a powerful tool for automation.
Group Policy settings can also manage Task Scheduler. This makes it easier to set up and keep tasks the same across multiple systems. It helps maintain order and efficiency.
The Task Scheduler has APIs for creating custom tools for tasks. Developers can use these APIs to build manage tasks uniquely. It opens opportunities for custom task management solutions.
Windows Server 2022 Task Scheduler is great for task automation. It covers scheduling, triggers, advanced actions, and more. It helps users improve how they handle tasks and boost system performance.
To get more info on Windows Server 2022 Task Scheduler, visit the official documentation.
Windows Server Task Scheduler Files Storage Location
The Windows Server Task Scheduler files are saved in three places. They include a file system location and two registry spots.
The file system spot is “C:\Windows\System32\Tasks”. It holds XML files with task settings. Remember this for troubleshooting or making backups.
Also, two places in the registry keep Task Scheduler files. These are: HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks and HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree.
It’s key to know where Task Scheduler files are kept. This helps with managing or fixing tasks on Windows Server. Whether for troubleshooting or backing up, this knowledge is useful.
Conclusion
Using the Task Scheduler to restart your Windows Server is crucial for maintenance and to keep it running smoothly. By setting up restarts following the steps here, you can manage your tasks efficiently. However, rebooting daily could hide deeper issues, as pointed out in discussions among IT experts.
Instead of daily reboots, aim for a monthly restart. This is a balanced approach, ensuring maintenance without causing too many interruptions. For VDI setups, more frequent reboots may be necessary. But, modern systems can handle this well, as mentioned by some experts.
It’s key to reboot servers only for important reasons like updates or fixing hardware. Focus on monitoring the health of your servers regularly, advises experts. Sometimes, shutting down servers at night might be needed for business reasons, affecting operations.
In sum, scheduling regular restarts using the Task Scheduler is the best way to manage your Windows Server. Find the right balance based on your server’s needs and advice from the IT community. This will keep your server running smoothly, reducing issues and managing maintenance effectively.
FAQ
How do I schedule a restart on Windows Server?
To schedule a restart on Windows Server, use the Task Scheduler. The article will guide you through setting a specific restart time.
Can I automate restarts on Windows Server 2022?
Yes, you can automate restarts on Windows Server 2022 with the Task Scheduler. There’s a step-by-step guide in the article for automating restarts.
How do I schedule a weekly backup on Windows Server 2022?
For a weekly backup on Windows Server 2022, try AOMEI tools like Backupper Server or Cyber Backup. These programs help you set up scheduled backups to keep your data safe.
What are the features of Windows Server 2022 Task Scheduler?
Windows Server 2022 Task Scheduler has features such as event triggers and better PowerShell support. It also offers improved logs, Windows Admin Center integration, and stronger security.
How can I troubleshoot tasks in Windows Server 2022 Task Scheduler?
If tasks aren’t working right, you can troubleshoot in several ways. These include checking logs, task settings, and testing tasks. You can also use Event Viewer or PowerShell for more details.
Can I automate task management with Windows Server 2022 Task Scheduler?
Yes, automating task management is possible with the Windows Server 2022 Task Scheduler. The article lists methods like PowerShell, Group Policy, Task Scheduler APIs, and automation tools.
Where are the Windows Server Task Scheduler files stored?
The files for Windows Server Task Scheduler are mostly kept in “C:\Windows\System32\Tasks”. This is where the task settings and configurations are stored.
How can I effectively schedule restarts on Windows Server?
The article explains how to effectively time restarts on Windows Server. Using the Task Scheduler, you can easily set up your restart schedule.
Source Links
- https://www.ubackup.com/windows-server/server-2019-schedule-reboot-0025-rc.html
- https://community.spiceworks.com/t/rebooting-a-server-after-installing-updates-how-soon/674783
- https://www.ubackup.com/windows-server/windows-server-2022-task-scheduler-8523-gc.html
- https://community.spiceworks.com/t/schedule-windows-server-to-reboot/1004131
- https://learn.microsoft.com/en-us/windows-server-essentials/manage/set-up-or-customize-server-backup
- https://www.partitionwizard.com/news/windows-server-backup-schedule-not-running.html
- https://learn.microsoft.com/en-us/troubleshoot/windows-server/system-management-components/schedule-server-process
- https://community.spiceworks.com/t/windows-2022-scheduler-issues/948554
- https://stackoverflow.com/questions/2913816/how-to-find-the-location-of-the-scheduled-tasks-folder
- https://community.spiceworks.com/t/daily-rebooting-servers-yes-or-no/945357
- About the Author
- Latest Posts
Mark is a senior content editor at Text-Center.com and has more than 20 years of experience with linux and windows operating systems. He also writes for Biteno.com
Task Scheduler
The Task Scheduler is a Windows component that can automatically run tasks at a specific time or in response to a specific event. For example, tasks can be run when the computer starts or when a user logs in. You can start tasks when a specific event occurs and using task scheduler you can run commands and execute scripts on a specific day and time.
Getting Started
Search task scheduler in Windows search.
Right-click on Task Scheduler and click New Folder and give a name to the folder like Server Reboot and click OK.
Making a folder makes your tasks separate, so you can manage easily.
Now right-click on new created folder and select Create Task.
Give a task name and description and select Run whether user is logged on or not and select Run with highest privileges in General tab.
Now click on Triggers tab, which is for restart scheduling date and time. In my trigger I am choosing to run this task every week on Sunday only, you can choose based on your requirement.
Click New.. button to create a new trigger and select required details and click OK.
Now let’s go to Actions tab, click new button to create an action. Enter Program/script path and arguments and start in values and click OK.
Now select Conditions tab and keep power settings as it if nothing needed.
Now click on Settings tab. I am stopping my task if runs longer than 2 hours and click OK.
Now you can see your task is ready to run on given schedule if you want to run anytime just hit the Run button.
Conclusion
In this article, we have learned how to create a new task and set up a server restart using Windows 10 Task Scheduler.
Как сделать автоматический запуск(перезапуск) службы windows по расписанию? С таким вопросом я столкнулся совсем недавно, участвуя в одном из проектов по своей работе. Решение оказалось достаточно простым.
Настройка автоматического запуска или перезапуска службы осуществляет в два простых шага:
- Шаг 1 — создать сценарий запуска/перезапуска службы.
- Шаг 2 — создать задачу и настроить расписание ее выполнения.
Создание сценария для службы
Сценарий запуска/перезапуска службы представляет собой обычный батник (bat-файл), который будет содержать команды:
1. Для запуска службы
net start [Имя службы] - запуск службы
2. Для перезапуска службы
net stop [Имя службы] - остановка службы net start [Имя службы] - запуск службы
Пример файла перезапуска службы windows
В качестве примера использована служба KMService.
Итак, создаем батник (bat-файл) с командами для перезапуска службы, который будет содержать две строки:
net stop KMService
net start KMService
Для обеспечения автоматического выполнения сценария перезапуска службы по расписанию: создается специальная задача, которая будет выполнять сценарий (запускать батничек).
Для создания задачи необходимо перейти в «Панель управления», кликнув в меню «Пуск» на пункт «Панель управления».
Далее, переходим в раздел «Администрирование».
В разделе «Администрирование» необходимо выбрать пункт «Планировщик заданий».
В окне «Планировщик заданий» кликаем правой кнопкой мыши на «Планировщик заданий» и выбираем пункт меню «Создать задачу».
В окне «Создание задачи» указываем Имя задачи, ставим галочку «Выполнить с наивысшими правами» и переходим на вкладку «Триггеры».
На вкладке «Триггеры» отображаются задаются условия запуска задачи. Для того чтобы создать расписание задачи перезапуска службы нажимаем на кнопку «Создать».
Заполняем параметры расписания задачи по перезапуску службы windows и нажимаем кнопку «Ок».
После создания расписания запуска задачи, необходимо указать наш сценарий(батничек), который должен выполнятся по расписанию. Для этого, переходим на вкладку «Действия» и нажимаем кнопку «Создать».
В окне «Создание действия» выбираем действие — «Запуск программы». После этого, нажимаем на кнопку «Обзор», ищем и выбираем наш файл со сценарием и нажимаем на кнопку «Ок».
И наконец, в окне «Создание задачи» нажимаем на кнопку «Ок».
Готово! Если все было сделано правильно, то задача будет выполняться по расписанию и будет перезапускать выбранную службу windows.
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
|
1 |
|
04.04.2018, 07:02. Показов 41933. Ответов 14 Здравствуйте! Если есть профессионалы PowerShell помогите написать скрипт на перезапуск служб на сервере по субботам и воскресеньям каждые 15 мин.
__________________ 0 |
1882 / 1106 / 426 Регистрация: 22.01.2016 Сообщений: 3,050 |
|
04.04.2018, 12:06 |
2 |
Сообщение от 1marcus написать скрипт на перезапуск служб на сервере по субботам и воскресеньям каждые 15 мин. Создаёте в планировщике Windows задание для выполнения powershell.exe с параметрами: Код -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -Command "&{Stop-Service Spooler; Start-Service Spooler}" и настраиваете нужное расписание для повторных запусков. 0 |
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
|
04.04.2018, 12:19 [ТС] |
3 |
Если вас не затруднит: 0 |
KDE777 1882 / 1106 / 426 Регистрация: 22.01.2016 Сообщений: 3,050 |
||||
04.04.2018, 12:26 |
4 |
|||
Сообщение от 1marcus 1.Покажите,пожалуйста,на скринах(Создаёте в планировщике Windows задание для выполнения powershell.exe с параметрами) Запуск PowerShell скриптов по расписанию Use the Windows Task Scheduler to Run a Windows PowerShell Script Сообщение от 1marcus 2.Возможно ли все-таки средствами Powershell написать такой скрипт? Весь скрипт на Powershell выглядит так (перезапуск службы «Диспетчер печати»):
А вот для запуск по расписанию нужен планировщик. 0 |
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
|
04.04.2018, 13:07 [ТС] |
5 |
Спасибо большое,буду пробывать. Вопросы появяться напишу Добавлено через 13 минут -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -Command «&{Stop-Service Spooler; Start-Service Spooler 0 |
1882 / 1106 / 426 Регистрация: 22.01.2016 Сообщений: 3,050 |
|
04.04.2018, 13:25 |
6 |
Сообщение от 1marcus Код, который вы указали получается нужно вставить в самом планировщике во вкладку «действия» затем «создать» и тут в активную строку «программа или сценарий»? Действие это — запуск программы, имя программы powershell.exe, а код показанный в ответе #2 нужно прописать в поле «Добавить аргументы» (Add arguments) Сообщение от 1marcus Можете часть кода расшифровать,а именно ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -Command «& Это параметры для запуска powershell.exe, все они подробно описаны, если перейти по первой ссылке из моего предыдущего ответа. 0 |
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
||
05.04.2018, 07:44 [ТС] |
7 |
|
Доброе утро! Добавлено через 45 минут В чем может быть причина? Вложения
0 |
KDE777 1882 / 1106 / 426 Регистрация: 22.01.2016 Сообщений: 3,050 |
||||
05.04.2018, 09:44 |
8 |
|||
Сообщение от 1marcus Если у меня имеется 2 службы
или строчка с параметрами: Код -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -Command "&{Stop-Service crypmail,crypoutmail; Start-Service crypmail,crypoutmail}" Добавлено через 1 минуту Сообщение от 1marcus В чем может быть причина? Покажите нормальный скриншот 0 |
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
|
05.04.2018, 11:21 [ТС] |
9 |
Пожалуйста,распакуйте архив,там вордовкий файл со скринами.Напрямую с сервера не могу снять,т.к права ограничены 0 |
KDE777 |
05.04.2018, 11:54 |
Не по теме: Сообщение от 1marcus Пожалуйста,распакуйте архив,там вордовкий файл со скринами. Спасибо, но в таком виде пусть смотрит кто-нибудь другой 0 |
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
|
05.04.2018, 16:47 [ТС] |
11 |
KDE777 Кликните здесь для просмотра всего текста 0 |
1882 / 1106 / 426 Регистрация: 22.01.2016 Сообщений: 3,050 |
|
05.04.2018, 17:21 |
12 |
Сообщение от 1marcus Вот скрины Ещё раз прочитайте мой ответ: Сообщение от KDE777 Действие это — запуск программы, имя программы powershell.exe, а код показанный в ответе #2 нужно прописать в поле «Добавить аргументы» (Add arguments) Никаких файлов start.ps1 я вам создавать не предлагал и тем более писать в Powershell-скрипте параметры для запуска powershell.exe! 0 |
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 11 |
|
09.04.2018, 11:47 [ТС] |
13 |
KDE777: Подскажите, а можно это реализовать в виде скрипта на PowerShell? Т.е. нужен сам скрипт чтобы отрабатывал перезапуск служб по выходным. 0 |
Maks Модератор 6871 / 3818 / 477 Регистрация: 13.03.2013 Сообщений: 14,058 Записей в блоге: 9 |
||||
03.05.2018, 08:27 |
14 |
|||
Сообщение от 1marcus Здравствуйте! Если есть профессионалы PowerShell помогите написать скрипт на перезапуск служб на сервере по субботам и воскресеньям каждые 15 мин. Есть алтернативное решение, например, написать батник
Далее, создать задание в планировщике с требуемыми триггерами (выходные, каждые 15 мин.) и указать путь к данному скрипту. 0 |
1882 / 1106 / 426 Регистрация: 22.01.2016 Сообщений: 3,050 |
|
03.05.2018, 12:20 |
15 |
Сообщение от Maks создать задание в планировщике с требуемыми триггерами (выходные, каждые 15 мин.) и указать путь к данному скрипту Именно это, и было сразу же предложено автору темы — запускать нужный скрипт из планировщика. Однако 1marcus, хочет получить реализацию функционала планировщика с помощью непосредственно скрипта Сообщение от 1marcus нужен сам скрипт чтобы отрабатывал перезапуск служб по выходным 0 |
Имеем Windows Server 2012 R2. Задача — автоматически перезагружать сервер каждый понедельник в 5 утра. Приступаем.
Запускаем Планировщик заданий, создаём в нём папку «reboot»:
Делаем Create Basic Task… Запускается мастер:
Указываем Name, Description:
Кликаем Next:
Выбираем период Weekly. Next:
Указываем начало — ближайший понедельник 5 утра. Ставим галку Monday. Next:
Выбираем Start a program. Next:
В Program/script: пишем:
%SYSTEMROOT%System32shutdown.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.
Две недели прошло — шедулер нормально перезагружает сервер по понедельникам.
- Remove From My Forums
Запуск службы с помощью планировщика.
-
Вопрос
-
Коллеги, добрый день. Пытаюсь создать задание в планировщике для запускаостановки необходимых служб по расписанию. Конечно можно сделать с помощью батника, но это не интересно:)
Создал задание, настроил запуск от пользователя «Администратор» и выполнять вне зависимости от регистрации пользователя.
Добавил действие. Запуск программы C:WindowsSystem32net.exe start «Name_services».
При запуске выдает last result 0x2.
На Windows Server 2012 такой шаблон запуска служб у меня работает. В чем может быть причина?
Ответы
-
Проблему решил. Помогло добавление пользователя в политику «Вход в качестве пакетного задания».
-
Предложено в качестве ответа
30 августа 2016 г. 10:41
-
Помечено в качестве ответа
Anton Sashev Ivanov
30 августа 2016 г. 10:53
-
Предложено в качестве ответа
Известно, что при функционировании рабочих процессов сервера 1С Предприятия 8.1 rphost.exe существует следующая проблема: из-за особенностей платформы, с подключением каждого нового клиента к рабочему процессу, увеличивается размер занимаемой рабочим процессом оперативной памяти. При этом, при отключении клиента, занимаемый при подключении объем не освобождается. Так же объем памяти, занимаемый рабочим процессом может увеличиваться при выполнении программного кода. Данное поведение называется “Утечками памяти” или “Memory Leaks”. В итоге, когда объем занимаемой памяти процессом rphost.exe вырастает больше опеределенного предела (в моем случае это было >1Gb), рабочий процесс безусловно перезапускается. Понятно, что клиенты, подключенные к этому процессу, получают сообщение, что соединение с сервером разорвано, прекращают работу и вынуждены переподключаться. В зависимости от количества пользователей и количества запущенных рабочих процессов, данная проблема возникает с той или иной частотой. В моем случае — пользователей порядка 60 и один рабочий процесс, подобная ситуация возникала до 5 раз в неделю. Т.е. ни о какой стабильной работе системы 1С Предприятие в этом случае речь не идет.
Первым шагом решения проблемы было — увеличить количество рабочих процессов, что и было сделано. Однако, проблему это решило лишь отчасти, перезапуски рабочих процессов стали происходить реже, но не исчезли совсем.
Второй и вполне логичный шаг — автоматический перезапуск процессов на сервере, о чем, собственно, и хочется написать.
Поскольку служба агента сервера 1С Предприятия представляет собой стандартную службу, в арсенале Windows есть стандартный способ остановки и запуска служб из командной строки командами net stop и net start. Достаточно эти команды лишь включить в bat-файл и настроить шедулер на запуск bat-файла по расписанию, я настроил перезапуск один раз в сутки, в ночное время. Следует иметь ввиду, что если перезапускать рабочие процессы в рабочее время, все подключенные к серверу 1С Предприятия клиенты будут отключены!
Кроме того, чтобы немного разнести по времени команды остановки и запуска службы, будем использовать известную утилиту sleep.exe, которую легко найти в Сети.
Примерный текст bat-файла restart1c.bat:
rem @echo off rem ----- начало скрипт остановки и запуска агента сервера 1С Предприятия---- set logfile="stopstartlog.txt" set timeout=20 echo %date% %time% >>%logfile% net stop "1C:Enterprise 8.1 Server Agent" >>%logfile% c:scriptssleep %timeout% echo %date% %time% >>%logfile% net start "1C:Enterprise 8.1 Server Agent" >>%logfile% c:scriptssleep %timeout% rem ----- конец скрипт остановки и запуска агента сервера 1С Предприятия----
Объяснение используемых переменных и команд:
* logfile — файл stopstartlog.txt, куда будут записываться результаты выполнения команд, размещается в том же каталоге, что и сам bat-файл;
** timeout — время в секундах;
*** c:scripts — каталог, где предполагается разместить программу sleep.exe, bat-файл и лог-файл;
Из этого же bat-файла можно сразу после перезапуска процессов запускать скрипт бэкапа средствами 1С Предприятия. В этом случае у вас гарантированно не будет подключен ни один клиент.
Необходимая ремарка: у пользователя, под которым будет выполняться задание по перезапуску службы должны быть соответствующие права на остановку и запуск служб сервера.
Источники:
- материалы форума www.mista.ru;
- Документация по платформе 1С Предприятие 8.1;
- Документация по продуктам MS Windows;
Windows, Windows 10, Windows 11, Windows 7, Windows 8, Windows Server, Windows Vista, Windows XP
- 19.10.2022
- 694
- 0
- 1
- 1
- 0
- Содержание статьи
- Настройка перезапуска службы Windows
- Добавить комментарий
Службами в Windows называют программы, которые работают в фоновом режиме, и обычно не требуют никакого взаимодействия с пользователем. Чаще всего, в роли служб выступают какие-то важные программы, которым необходимо быть постоянно запущенными. Однако, поскольку никто не застрахован от каких-либо ошибок в работе аппаратных или программных средств компьютера, такая программа может завершить свою работу в самый неподходящий момент. Чтобы избежать столь неприятного поворота событий, в настройках служб Windows предусмотрена возможность настройки перезапуска служб, в случае её непредвиденного завершения работы.
Настройка перезапуска службы Windows
- Открываем консоль управления службами, и находим нужную службу.
- Открываем свойства нужной службы, и переходим на вкладку «Восстановление».
- На данной вкладке можно настроить поведение службы при её непредвиденном завершении. При этом, есть возможность настроить различные действия для первого, второго и последующего завершения работы.
Для выбора доступны следующие действия:
- Не выполнять никаких действий — в таком случае, ничего не будет делаться.
- Перезапуск службы — служба будет повторно запущена.
- Запуск программы — можно запустить программу или скрипт, например скрипт для отправки оповещения по электронной почте.
- Перезагрузка компьютера — как должно быть понятно из названия данного пункта, компьютер будет перезагружен.
Таким образом, для перезапуска службы в случае её завершения, достаточно выставить значение «Перезапуск службы» во всех трех пунктах.
- На главную
- Категории
- Прочее
- Автоматический перезапуск службы агента сервера 1С — скрипт + расписание
Добрый день. Поступила заявка от 1С-ников, что необходимо ночью перезапускать службу агента сервера 1С на 8-ке. Как многим известно, что данную службу просто так нельзя «перезапустить», иначе зависшие сессии так и остаются «висеть», ее необходимо сначала остановить, а после снова запустить. Порывшись немного в интернете, пересмотрев кучу скриптов — собрал из многообразия один, не большой, полностью рабочий, уже оттестировал его на серверах, теперь выкладываю на ваше обозрение и пользование.
2017-10-12 09:53:53215
Скрипт перезапуска службы агента сервера 1С
В данном разделе я приведу скрипт .bat, который у меня получился, а так же дам краткое описание того, что за что отвечает в моем случае.
Собственно сам скрипт:
@echo off
set logfile="C:!Distrscriptstopstartlog.txt" echo %date% %time% >>%logfile%
net stop "1C:Enterprise 8.3 Server Agent (1640)" >>%logfile%
ping -n 16 localhost>Nul echo %date% %time% >>%logfile%
net start "1C:Enterprise 8.3 Server Agent (1640)" >>%logfile%
ping -n 301 localhost>Nul SetLocal EnableExtensions
Set ProcessName=1C:Enterprise 8.3 Server Agent (1640)
TaskList /FI "ImageName EQ %ProcessName%" | Find /I "%ProcessName%" If %ErrorLevel% NEQ 0 net start "1C:Enterprise 8.3 Server Agent (1640)"
exit
Давайте рассмотрим его подробнее:
- Первым делом отключаем уведомления о выполнении, пусть это все работает в фоновом режиме
- Далее указываем где будет хранится наш лог-файл, куда будет писаться дата и время запуска и остановки службы (можно не писать лог, но на всякий случай пусть будет)
- Пишем в Лог дату и время начала остановки
- Останавливаем службу агента сервера, в моем случае она называется так — 1C:Enterprise 8.3 Server Agent (1640) и пишем ее статус в лог файл (ниже приведу пример что в логе появляется)
- Далее делаем задержку в 15 секунд, чтобы дождаться, пока служба останавливается (пинг равен примерно 1 секунде, первый проходит моментально, поэтому делаем время в секундах +1)
- Опять записываем в лог дату в время
- Запускаем службу обратно
- Делаем задержку в 5 минут, если служба не остановилась за 15 секунд, то она не запустится естественно, что то видимо зависло сильно и будем ждать 5 минут.
- Далее проверяем, запустилась ли служба и работает ли она? Если не работает, то выполняем ее повторный старт.
- Завершаем работу с cmd.
Все, вот такой вот получился скрипт. Я не программист, поэтому может он не совсем верный с точки зрения выполнения сценариев и программного кода, но для меня важно, чтобы это работало — а это работает! Данный скрипт у меня выполняется каждый день, каждый час с 00:00 до 7:00, но об этом позже.
Пример лог файла:
12.10.2017 0:00:00,10
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" останавливается.....
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" успешно остановлена.
12.10.2017 0:00:15,33
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" запускается.
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" успешно запущена.
12.10.2017 1:00:00,15
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" останавливается....
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" успешно остановлена.
12.10.2017 1:00:15,37
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" запускается.
Служба "Агент сервера 1С:Предприятия 8.3 (1640)" успешно запущена.
Настройка выполнения *.bat по расписанию
Как я уже говорил выше, выполнение скрипта у меня происходит автоматически, каждый день он запускается ежечасно с 00:00 до 7:00. Сейчас я расскажу, как это сделано у меня.
Для начала идем в «Пуск -> панель управления -> Администрирование» и запускаем там «Планировщик заданий«.
Выбираем пункт «Создать задачу«:
На вкладке «Общие» задаем имя задания, его описание и пользователя, от которого оно будет выполняться. По умолчанию там будет пользователь, под которым вы вошли в данный момент в систему.
Далее идем в закладку Триггеры и настраиваем, когда нам надо запускать задачу. В моем случае это ежедневно выполнять в 00:00 и повторять ее каждый час в течении 7 часов.
Далее идем во вкладку Действия и создаем действие на выполнения скрипта.
Все, на этом все готово. Как можем увидеть в журнале, задача с такими параметрами успешно выполняется и ровно то время, которое у нас задано в скрипте:
Заключение
Вот так не очень сложно создается скрипт на перезапуск службы агента сервера 1С и настраивается его расписание. Я думаю что многие итак знают как сделать одно или второе, но я думаю что кому то это пригодится. Если у Вас возникнут проблемы или вопросы — задавайте их в комментариях, постараюсь помочь чем смогу. Если будут какие-то дополнения или предложения — с удовольствием тоже выслушаю.
Так же можно почитать про скрипт — удаление файлов старше n дней
Ваш покорный слуга — компьютерщик широкого профиля: системный администратор, вебмастер, интернет-маркетолог и много чего кто. Вместе с Вами, если Вы конечно не против, разовьем из обычного блога крутой технический комплекс.
Managing a Windows server can be a daunting task, especially when you have to keep it running 24/7. However, it is important to give your server a break to avoid potential issues caused by prolonged uptime. One simple solution is to schedule an automatic restart on a regular basis. In this tutorial, we will guide you through the steps to set up an automatic restart for your Windows server every Sunday.
Step 1: Open Task Scheduler
The first step is to open the Task Scheduler on your Windows server. You can do this by typing “Task Scheduler” in the Start menu and clicking on the result. Alternatively, you can open the Run dialog by pressing the Windows key + R and then typing “taskschd.msc” before hitting Enter.
Step 2: Create a New Task
In the Task Scheduler window, click on the “Create Task” option in the right panel. This will open a new window where you can configure the details of the task.
Step 3: Configure the Task Settings
In the “General” tab of the new task window, give your task a name such as “Automatic Restart”. You can also provide a description if you wish.
Next, make sure to select “Run whether the user is logged on or not” and “Run with highest privileges” options. You can also choose the operating system that this task will run on by selecting the appropriate option in the “Configure for” dropdown list.
Step 4: Schedule the Task
In the “Triggers” tab, click on the “New” button to create a new trigger. Set the “Begin the task” dropdown to “On a schedule” and choose the frequency of the restart by selecting “Weekly”. Select the “Sunday” option and set the time that you want the restart to occur. You can also set the task to recur every week if you wish.
Step 5: Configure the Action
In the “Actions” tab, click on the “New” button to create a new action. Set the “Action” dropdown to “Start a program” and type “shutdown” in the “Program/script” field. In the “Add arguments” field, type “-r -t 0” to specify that the server should restart and that it should do so immediately, without waiting.
Step 6: Save the Task
Once you have completed all the steps, click on the “OK” button to save the task. You will be asked to enter your administrator password to confirm your changes.
Congratulations, you have now set up an automatic restart for your Windows server every Sunday! This simple solution will help to keep your server running smoothly by giving it a regular break to refresh its system resources.
Buy Windows Shared Server