Планировщик задач windows server 2008

Здесь я расскажу как создать простую задачу в планировщике задач в Windows Server 2008.

1. Постановка задачи

Предположим, что нам надо запускать файл «С:\Example\start.bat» в течении суток каждые 20 мин. Файл start.bat будет просто записывать в текстовый файл log.txt время своего запуска. Вот его содержание:

2. Добавление новой задачи

Запускаем диспетчер сервера («Пуск» — «Администрирование» — «Диспетчер сервера»). Раскрываем меню «Конфигурация» , затем «Планировщик заданий» и выделяем вкладку «Библиотека планировщика заданий» . Затем справа, в окне «Действия» , нажимаем «Создать папку…» .

Вводим имя — я ввожу «Мои задачи» — и видим что рядом с заданиями Microsoft появилась папка с только что введенным именем. Выделим ее и в меню «Действия» нажмем «Создать задачу» .

Запустится окно «Создание задачи» . В поле «Имя» вводим название задачи, при желании можно заполнить «Описание задачи» . Ниже необходимо указать учетную запись для запуска задачи. Обычно со временем на сервере накапливается много разных задач, и я, как правило, создаю отдельную учетную запись для их выполнения (как создать новую учетную запись можно прочитать здесь). Если вы хотите сменить пользователя для задачи нажимаем «Изменить» , затем «Дополнительно» , в появившемся окне нажимаем «Поиск» и выбираем пользователя из списка.

Далее устанавливаем переключатель на «Выполнять вне зависимости от регистрации пользователя» и в меню «Настроить для» выбираем «Windows 7, Windows Server 2008 R2» .

Теперь переходим на вкладку «Триггеры» и нажимаем «Создать» . Откроется окно «Создание триггера» . Здесь, в соответствии с поставленной задачей, выбираем:

  • Параметры — «Ежедневно» ;
  • Начинать с — устанавливаем время «11:00:00» ;
  • Повторять каждые — «1 дн.» ;
  • Установим флаг «Повторять задачу каждые:» и т. к. в списке нет нужного нам интервала, вручную напишем «20 мин.» в течение «Бесконечно» ;

Novaya_Zadacha_006

Или же можно создать 3 разных триггера с интервалом исполнения 1 час и началом действия соответственно: 11:00, 11:20 и 11:40.

В обоих случаях задача будет запускаться каждые 20 минут.

Далее, на вкладке «Действия» нажимаем «Создать» и указываем путь к нашему файлу.

При необходимости можно заполнить вкладки «Условия» и «Параметры» . В нашем примере этого не требуется. После сохранения задачи, она должна появиться в списке задач. (При определении нескольких триггеров, время следующего запуска задачи показывается в таблице не правильно — по первому триггеру. Несмотря на это задача запускается как положено.)

Все, на этом создание новой задачи закончено. По прошествии часа файл log.txt должен содержать записи:

The
Task Scheduler in Windows Server 2008 R2 replaces the Scheduled Tasks
tool that was literally unchanged since the release of Windows 98. The
main focal point of the tool is to assist administrators by automating
tasks. In addition, by consolidating standard and reoccurring tasks
into a central location, administrators gain insight into system
functionality and control over their Windows Server 2008 R2
infrastructure through automation. These things together assist
administrators in the areas of logging and debugging.

Windows Server 2008 R2
improves upon the previous version of the Scheduled Task tools included
in Windows Server 2003 by allowing scheduled jobs to run more securely
and with greater predictability. One of the most compelling new features
of the Task Scheduler is that it fully integrates with Event Viewer. As
such, a task can be triggered based on an event captured in the event
log. This is a great feature because administrators can be automatically
notified when a specific event transpires.

Understanding Task Scheduler

Scheduling tasks involves
triggers and actions. A task runs once it is triggered. Tasks are
initiated by triggers that are based on an event or time. Multiple
triggers can be associated with a task as defined by an administrator.
An action represents the work being performed as the task is being
executed. Examples of actions include starting a program or sending an
email. When a task is running multiple actions, up to 32 can be
performed.

An additional
functionality is task conditions. When a task is triggered, it will only
run if specific defined conditions are met. Task conditions eliminate
ambiguous situations by providing criteria-based functions. By improving
on the Task Scheduler’s functionality, it has become a very powerful
and extensive development and activation tool for automating and
assisting with troubleshooting tasks.

With Windows Server 2008
R2, Task Scheduler has been moved from Control Panel to Administrative
Tools. The new user interface is displayed in Figure 1.

Figure 1. The Task Scheduler user interface.



Tasks
are created by selecting Create Basic Task, Create Task, or Import Task
from the Actions pane in the Task Scheduler snap-in. When creating a
task, there are five tabs of options that must be configured. They
include general settings, triggers, actions, conditions, and additional
settings. The upcoming sections explain the options when creating tasks.

Understanding Trigger Options and Settings

The first thing to consider
when configuring a task is what triggers will cause the task to
execute. Triggers can be based on time, events, or various system
states. As noted earlier, each task can contain multiple triggers. With
more than one trigger, the task will launch when any of the conditions
in any of the triggers is met.

The following describes the various trigger types and the settings that can be configured for each type:

  • On a Schedule—
    Triggers for a schedule allow tasks to run on a specific date (one
    time), Daily, Weekly, or Monthly. For reoccurring tasks, the start time
    can be configured along with reoccurring options to completely customize
    when the task will run.

  • At Log On— Tasks scheduled to run when At Log On is set for any user or for a specific user or group of users.

  • At Startup—
    There are no specific settings for tasks configured to run at startup.
    This type of trigger runs whenever the system starts and the only
    settings are the advanced ones, which are described later in the
    chapter.

  • On Idle— The settings for tasks set to run when the computer is idle are set on the Conditions tab.

  • On an Event—
    This trigger causes a task to run when specific events are created in
    an event log. You can choose either a basic event trigger or custom
    event settings. Basic settings fire based on a single event from a
    specific event log. You choose which log contains the event, the
    publisher name, and the event ID. If you specify the custom event
    trigger settings, you can specify an XML event query or custom event
    filter to query for events that will fire the task.


  • At Task Creation/Modification—
    Tasks created with this trigger are fired as soon as they are created
    or whenever they are modified. The only settings for this trigger are
    the advanced settings as described in the next section, “Understanding the Advanced Settings Associated with Triggers.”

  • On Connection to User Session—
    The trigger fires when a user connects to the system using the Remote
    Desktop Connection program from another system and can be set to run
    when any user connects, or when a specific user or group connects to the
    server.

  • On Disconnect from User Session—
    This trigger works the same as the On Connection to User Session;
    however, it fires when users disconnect from the server from a Remote
    Desktop Connection session. The trigger can be set to run for all users
    or a specific user or group.

  • On Workstation Lock—
    The trigger fires when the workstation is locked. The settings for this
    trigger enable you to set it for all users or a specific user or group.

  • On Workstation Unlock—
    This trigger fires when the workstation is unlocked. The settings for
    this trigger enable you to set it for all users or a specific user or
    group.

Understanding the Advanced Settings Associated with Triggers

Advanced settings
exist when creating triggers. Familiarize yourself with these advanced
settings to ensure trigger creation and the workflow process is fully
optimized. The following bullets explain each of the advanced settings
associated with triggers:

  • Delay Task for or Delay Task for Up To (Random Delay)—
    Tasks can be delayed randomly so that they do not start immediately
    when the schedule triggers a task. For systems that might run the same
    tasks, this ensures there is some load balancing and
    that all systems do not run tasks at exactly the same time. Random
    delays can be set for 30 seconds, 1 minute, 30 minutes, 1 hour, 8 hours,
    or up to 1 day.

  • Repeat Task Every—
    Tasks can also be set to repeat at regular intervals and for a set
    duration (for example, a task could be set to ping a particular system
    every minute for 1 day, write an event to the event log in the case of a
    failure, and email a distribution group to notify the IT team about the
    issue).

  • Stop Any Task If It Runs Longer Than— Tasks can be stopped if they run past a defined amount of time and can be set to expire at a certain date and time.

  • Start and Expire—
    Start and Expiration times can be set to synchronize across time zones
    to ensure tasks set to run on systems in multiple time zones start and
    stop at the same time.

  • Enabled— Tasks can be enabled or disabled by checking or unchecking the enabled box.

Understanding the Actions Associated with a Task

As mentioned earlier, an action
is the work conducted when a task runs. Tasks can have a single action
or up to a maximum of 32 actions. The Actions tab of a task contains a
list of actions associated with a particular task. An administrator can
edit each action as follows:

  • Start a Program—
    This action starts a program or script. In the Program/Script text box,
    type either the name of the program or script that should be run.
    Alternatively, the administrator can browse the application or script.
    If further command-line arguments are required, these can be specified
    in the Add Arguments (Optional) text box. In the Start In (Optional)
    text box, the working directory can be specified for the command line
    that executes the program or script. This path is either the path to the
    program or script or to the files that are used by the executable.

  • Send an E-mail—
    This action sends an email when the task is triggered. In the Edit
    Action dialog box, you enter who the email is from, who it should be
    sent to, a subject, and any desired text. You must also enter a valid
    SMTP server.

  • Display a Message—
    This action simply displays a message on the console of the system
    where the task is created. You can enter a title for the message as well
    as any text that should be displayed. This type of action only launches
    if the Run Only If User Is Logged On security option has been selected
    on the General tab of the Task Properties in the Create Task dialog box.

Understanding Conditions Associated with a Task

Conditions in conjunction
with triggers determine whether the task will run. Tasks will not run
if any condition associated with a given task is not fulfilled. The
following sections illustrate the types of conditions associated with a
task:

  • Idle Conditions—
    A trigger can be based on idle time of a computer. Idle time is checked
    by the Task Scheduler service every 15 minutes. Computers are idle if a
    screensaver is running. When a screensaver is not running, the computer
    is considered to
    be idle if for 15 minutes the CPU usage and disk input or output were
    at 0% for 90% of the overall time. In this situation, mouse or keyboard
    input should also be nil during this period of time. The Task Scheduler
    service only waits for user input to mark the end of an idle state.

  • Power Conditions—
    Administrators can specify that tasks run only on computers operating
    on AC power. If administrators do not want a task to run when a computer
    is on battery power, a condition must be set to stop the task. Also, if
    the computer is off, a condition can be set to awaken the computer from
    a Sleep or Hibernate mode so the task can run. Although this is
    unlikely in a server environment, it’s still an option.

  • Network Conditions—
    Administrators can choose to start a task only if a specified network
    connection is available. This setting is appropriate if the action
    requires access to a remote system or network.

Note

The Network Conditions do not support interoperability with Windows 2000 or XP.


Understanding Task Settings

The Settings tab of the Tasks
Properties or Create Task dialog box offers settings that help you
control how the task is run, restarted, stopped, or deleted, as follows:

  • Allow Task to Be Run on Demand—
    If selected, this setting enables the administrator to manually start
    the task regardless of triggers or conditions by selecting the tasks and
    clicking Run in the Actions pane or right-clicking the task and
    selecting Run from the context menu.

  • Run Task as Soon as Possible After a Scheduled Start Is Missed—
    If this option is selected, a task that has been scheduled to start at a
    specific time but did not run (for example, the computer was off or the
    scheduler service was busy) will be started, but only after 10 minutes
    has elapsed from the original start time.

  • If the Task Fails, Restart Every—
    This setting controls what to do when a task does not run (for example,
    if a task fails to start a service due to an undetermined system
    problem). If this option is selected, an administrator can also
    configure the number of attempts that should be made to initiate the
    task.

  • If the Running Task Does Not End When Requested, Force It to Stop— If a task does not respond to a request to stop, an administrator can set a condition to force it to stop.

  • Stop the Task If It Runs Longer Than—
    If this item is checked, a limit on how long the task can run is
    enforced. As a result of this setting, a task might not be completed
    when it is stopped.

  • If the Task Is Not Scheduled to Run Again, Delete It After— This selection helps the administrator keep the Task Scheduler MMC free from old tasks that might have
    been put in place to accomplish a specific action but are no longer
    needed or will never be repeated. Note that a trigger must contain an
    expiration task.

  • If the Task Is Already Running: Do Not Start a New Instance— The task will not start a new instance if an instance of the task is already running.

  • If the Task Is Already Running: Run a New Instance in Parallel—
    A new task will run in parallel if one instance is running and the
    triggers and conditions cause the task to be triggered again.

  • If the Task Is Already Running: Queue a New Instance—
    A new task will queue, but it will not start until the first instance
    is complete and will not stop the instance that is already running.

  • If the Task Is Already Running: Stop the Existing Instance—
    A new task is triggered and conditions specified in the task will first
    stop the current instance and then start a new instance of the task.

Understanding Task History

The History tab on the
properties page for a task contains events filtered from the Operational
events for the Task Scheduler in the Event Viewer and enables an
administrator to see success and failures for any given task without
having to review all task-related event information for a system or
collection of systems.

Note

Although the Task
Scheduler enables an administrator to create folders for organizing
tasks and new tasks can be given meaningful names, after a folder or
task is created, it cannot be renamed. Further, tasks cannot be moved
from one folder to another. However, tasks can be exported and then
imported into a new folder or another system.

Прочитано: 1 478

Рассмотрим вариант создание заданий через командную строку:

На исходной машине alektest5 создадим задание о перезагрузке сервера каждый час:

Schtasks.exe /create /S alektest5 /RU Administrator /RP 712mbddr@ /SC HOURLY /TN shutdown /TR “%systemroot%\system32\shutdown.exe /r /f”

Создание задания в консоли.

, где

/S – имя удаленной / локальной машины.

/RU – От имени кого будем запускать наше задание

/RP – Пароль от имени кого будет запускать задание

/SC – С какой периодичностью будем запускать задание.

/TN – название задания

/TR – путь до исполняемой команды/батника.

Я указал у себя, что перезагружать сервер каждый час. Итогом будет окно вида:

В событиях

Server ManagerDiagnosticsEvent ViewerWindows LogsSystem отфильтровать по коду 1074.

Смотрим события выполнения задания.

Удалить все задания или конкретное:

Schtasks /delete /TN * /F

Schtasks /delete /TN “shutdown” /F

, параметры /TN “<ваше_название_задания>”.

Создание заданий с запуском внешнего скрипта:

Задание на запуск bat’ника в котором идет вывод текущей даты и времени каждую минуту и перенаправление в файл echo %date% %time% >> c:\1\1.txt

Schtasks /create /S alektest5 /RU Administrator /RP 712mdddr@ /SC MINUTE /TN time /TR “c:\1\bat” >> c:\1\1.txt

Задание с запуском внешнего скрипта.

Задание на запуск bat’ника в котором идет бекап прав каталога c:\windows\system32\ и сохранение его по адресу c:\1\acl_system32.txt каждый день в 17 часов и заканчивается 18 часами.

Schtasks /create /S alektest5 /RU Administrator /RP 712mbddr@ /SC DAILY /ST 17:00 /ET 18:00 /TN time /TR “c:\1\bat.bat”

Определенное время запуска задания.

Important Note: Windows Server 2008 is end of life and no longer supported by Microsoft. This is a knowledge base for legacy version support for window server 2008. For information on the latest version of windows server, you can refer to this link: Windows Server 2022 setup task scheduler

Introduction

This guide explains how to set up and configure Task Scheduler in Windows Server 2008. Task Scheduler is a tool that allows administrators to automate tasks like running scripts, launching programs, and performing system maintenance. This guide is intended for system administrators managing Windows Server environments who want to schedule regular tasks to automate server operations.

Prerequisites

Before proceeding, ensure you have the following:

  • Administrative access to the Windows Server 2008 instance.
  • The specific task (script or program) you want to automate.

Step-by-step guide

Step 1: Go to administrative tools, task scheduler.

Step 2: Then right-click on Task Scheduler and select Create Task

Step 3: Name the task, in this example “Reboot Weekly Saturday 2am”

Step 4: Change settings to run whether the user is logged in or not. Change User/Group and type in SYSTEM.

On the Triggers tab, select New and fill in your schedule and make sure to check Enabled at bottom of the screen.

Step 5: On the Actions tab, select New Action, Start a program, and browse to “c:.windows/system32/shutdown.exe” and add “/r” in the arguments box.

Conclusion

By following this guide, you can effectively set up automated tasks in Windows Server 2008 using Task Scheduler. Regularly scheduled tasks help reduce the manual workload and ensure consistent performance of system maintenance, backups, and custom scripts.

For additional assistance or if you encounter any issues, please contact our support team at support@ipserverone.com.

Article posted on 18 April 2020 by ips1

Планировщик заданий (Task scheduler) в Windows Server 2008 подвергся значительной модификации по сравнению с предыдущими версиями Windows Server. Теперь ключевыми элементами запланированных заданий стали триггеры (Triggers), действия (Actions), условия (Conditions) и параметры (Settings).

Набор настроек триггеров и действий запланированного задания в Windows Server 2008 значительно расширился. Среди стандартных триггеров – возможность начинать задачу по расписанию (On a schedule) при запуске компьютера (System boot) или при входе в систему (User logon).

Появились и новые триггеры:

«По событию» (Event trigger): запланированное задание начнет выполняться после того, как в журнале будет зафиксировано определенное событие.

«При подключении к пользовательскому сеансу» (User session connection): этот триггер аналогичен опции «При входе в систему», но предусматривает также возможность подключения к удаленному компьютеру и определения индивидуальных параметров для каждого пользователя.

«При отключении от пользовательского сеанса» (User session disconnection): выполнение задания начинается после отключения от пользовательской сессии без выхода из системы.

«При блокировании рабочей станции» (Workstation locking): выполнение задания начинается после блокировки компьютера из консоли.

Интерфейс выбора триггеров в Windows Server 2008 был значительно усовершенствован и стал чувствителен к контексту. На рис. A выбран триггер задания «При подключении к пользовательскому сеансу».

Возможности нового Планировщика заданий в Windows Server 2008

Рисунок A

Помимо триггеров, можно указать дополнительные правила для определения особых параметров выполнения задания и среды, в которой оно будет выполняться. К примеру, для большинства триггеров можно выбрать опцию отложенного выполнения задания, благодаря которой выполнение фоновых процессов не будет оттягивать на себя драгоценные ресурсы при запуске системы и в любых других ситуациях, когда между выполнением заданного условия и началом выполнения задания должен пройти какой-то период времени. На рис. B выбран параметр «Отложить на» (Delay Task For) для запланированного задания.

Возможности нового Планировщика заданий в Windows Server 2008

Рисунок B

Дополнительные настройки триггеров в Windows Server 2008 позволяют создавать более сложные правила для выполнения запланированных заданий в среде Windows. Однако чересчур сложные настройки запланированных заданий для каждого локального компьютера усложняют управление сетью в целом.

Автор: Rick Vanover

Перевод: SVET

Оцените статью: Голосов

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Сколько нужно места для точки восстановления windows 10
  • Как включить встроенную запись экрана на windows 10
  • Как свернуть приложение в windows на клавиатуре
  • Windows 10 панель управления классический вид
  • Run jar file on windows