Windows service start events

Service Trigger Events

A service can register to be started or stopped when a trigger event occurs. This eliminates the need for services to start when the system starts, or for services to poll or actively wait for an event; a service can start when it is needed, instead of starting automatically whether or not there is work to do. Examples of predefined trigger events include arrival of a device of a specified device interface class or availability of a particular firewall port. A service can also register for a custom trigger event generated by an Event Tracing for Windows (ETW) provider.

Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP: Service trigger events are not supported until Windows ServerВ 2008В R2 and WindowsВ 7.

A trigger consists of a trigger event type, a trigger event subtype, the action to be taken in response to the trigger event, and (for certain trigger event types) one or more trigger-specific data items. The subtype and the trigger-specific data items together specify the conditions for notifying the service of the event. The format of a data item depends on the trigger event type; a data item can be binary data, a string, or a multistring. Strings must be Unicode; ANSI strings are not supported.

To register for trigger events, the service calls ChangeServiceConfig2 with SERVICE_CONFIG_TRIGGER_INFO and supplies a SERVICE_TRIGGER_INFO structure. The SERVICE_TRIGGER_INFO structure points to an array of SERVICE_TRIGGER structures, each specifying one trigger.

The specified trigger action is taken if the trigger condition is true when the system starts, or if the trigger condition becomes true while the system is running. For example, if a service registers to be started when a particular device is available, the service is started when the system starts if the device is already plugged in to the computer; the service is started when the device arrives if the user plugs in the device while the system is running.

If a trigger has trigger-specific data items, the trigger action is taken only if the data item that accompanies the trigger event matches one of the data items that the service specified with the trigger. Binary data matching is done by bitwise comparison. String matching is case-insensitive. If the data item is a multistring, all strings in the multistring must match.

When a service is started in response to a trigger event, the service receives SERVICE_TRIGGER_STARTED_ARGUMENT as argv[1] in its ServiceMain callback function. Argv[0] is always the short name of the service.

A service that registers to be started in response to a trigger event might stop itself after an idle time-out when the service has no work to do. A service that stops itself must be prepared to handle SERVICE_CONTROL_TRIGGEREVENT control requests that arrive while the service is stopping itself. The SCM sends a SERVICE_CONTROL_TRIGGEREVENT control request whenever a new trigger event occurs while the service is in the running state. To avoid losing trigger events, the service should return ERROR_SHUTDOWN_IN_PROGRESS for any SERVICE_CONTROL_TRIGGEREVENT control request that arrives while the service is transitioning from running to stopped. This instructs the SCM to queue trigger events and wait for the service to enter the stopped state. The SCM then takes the action associated with the queued trigger event, such as starting the service.

Читайте также:  Dhcp how to linux

When the service is ready to handle trigger events again, it sets SERVICE_ACCEPT_TRIGGEREVENT in its controls-accepted mask in a call to SetServiceStatus. This is usually done when the service calls SetServiceStatus with SERVICE_RUNNING. The SCM then issues a SERVICE_CONTROL_TRIGGEREVENT request for each queued trigger event until the queue is empty.

A service that has dependent services running cannot be stopped in response to a trigger event.

Trigger-start and trigger-stop requests are not guaranteed under low memory conditions.

Use the QueryServiceConfig2 function to retrieve a service’s trigger event configuration.

The SC tool (sc.exe) can be used to configure or query a service’s trigger events at the command prompt. Use the triggerinfo option to configure a service to start or stop in response to a trigger event. Use the qtriggerinfo option to query the trigger configuration of a service.

The following example queries the trigger configuration of the W32time service, which is configured to start when the computer is joined to a domain and stop when the computer leaves the domain.

The following example queries the trigger configuration of the tablet input service, which is configured to start when a HID device with the GUID <4d1e55b2-f16f-11cf-88cb-001111000030>and any of the specified HID device IDs arrives.

The Core Technologies Blog

Our Software // Windows Services // 24×7 Operation

When did my Windows Service Start?

Here are four ways to determine when your windows service last started.

Solution #1: Search the Windows Event Logs with PowerShell

The Windows Event Logs hold a wealth of information about your computer’s activities. Indeed, a new record is added to the System event log whenever a windows service starts or stops.

The easiest way to find your service’s most recent start time is to use a specially crafted PowerShell command to search the System event log. For example, the following line will return the last time the “Print Spooler” service was started:

(Get-EventLog -LogName «System» -Source «Service Control Manager» -EntryType «Information» -Message «*Print Spooler service*running*» -Newest 1).TimeGenerated

Be sure to replace «Print Spooler» with the display name of the service you are investigating!

Solution #2: Search the Windows Event Logs using the Event Viewer

Instead of running a PowerShell command, you can also search the Event Log manually.

To find the event log record showing when your service was last started:

Open the Event Viewer from the Control Panel (search for it by name).

In the left-hand column, navigate to Windows Logs > System:

Click Find… on the right to bring up the Find window. Enter the name of the service and click the Find Next button to highlight the first matching record in the middle panel. We have entered Spooler, for the Windows Spooler service:

If necessary, keep clicking the Find Next button until a record saying that your service has “entered the running state” comes up. The Source should be Service Control Manager, and the time your service started will be displayed in the Logged value. The screenshot show that the Print Spooler service last started at 8:04:55 AM on January 7th 2017:

Solution #3: Figure out when the Service’s Process was Started

Each running windows service is backed by an underlying process. 99.9% of the time, that process was launched immediately when the service started. So finding the process start time will give us the service start time.

Читайте также:  Как создать новое окно windows 10

To find out when the service’s process was started:

Determine the process identifier (PID) of the service’s process using the SC command. For a service named MyService, run:

(Be sure to enclose the service name in quotes if it contains spaces.)

Here is the result for the Spooler service:

Make a note of the number on the PID line (1276 in the screenshot above).

Get-Process | select name, id, starttime | select-string

is the process identifier from step 1. The start time will come back in the result. Here is what we got for the spooler’s process (#1276):

Solution #4: Use the System Boot/Up Time (for Automatic Windows Services)

Most Windows Services start when your computer boots and run continuously, 24×7 in the background. For those services, the system boot time is a reasonable approximate.

You can run the built-in systeminfo command to discover when the system last started. Amongst the valuable information systeminfo returns, look for the “System Boot Time” line:

However, if you’re ever in a situation where you can’t remember the command to use, know that the Task Manager’s Performance tab shows how long the computer has been up (“Up time”). The system boot time is a simple calculation away.

So there are four easy ways to find out when your windows service started. Use whichever one best fits your situation. Good luck with your troubleshooting/investigation!

Медленная служба не запустится из-за ошибки времени простоя в Windows

В этой статье приводится обходное решение проблемы, из-за которой медленная служба не начинает работу из-за ошибки времени выполнения в Windows.

Исходная версия продукта: Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows 10 — все выпуски
Исходный номер КБ: 922918

Чтобы обойти эту проблему, измените реестр, чтобы увеличить значение времени простоя по умолчанию для диспетчера управления службами. Чтобы увеличить это значение до 60 секунд, выполните следующие действия.

Щелкните Пуск, затем Выполнить и введите regedit. Затем нажмите ОК.

Найдите и откройте следующий подраздел реестра:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control

На правой области найдите запись ServicesPipeTimeout.

Если запись ServicesPipeTimeout не существует, ее необходимо создать. Для этого выполните следующие действия:

  1. В меню Правка выберите пункт Создать, а затем Параметр DWORD.
  2. Введите ServicesPipeTimeout и нажмите ввод.

Щелкните правой кнопкой мыши ServicesPipeTimeout и выберите «Изменить».

Щелкните decimal, введите 60000, а затем нажмите кнопку ОК. Это значение представляет время в миллисекунах до того, как служба будет отсутизировать время.

  • Это обходное решение может устранить проблему, из-за которой служба не запустится. Тем не менее, рекомендуется исследовать эту проблему, чтобы определить, является ли она признаком другой проблемы.
  • Тщательно увеличийте это число. Мы рекомендуем увеличить это число с небольшим количеством за раз, пока служба не запустится.

Дополнительная информация

Диспетчер управления службой ждет время, указанное записью ServicesPipeTimeout, перед ведением журнала события 7000 или 7011. Для запуска служб, которые зависят от службы диспетчера сеансов трассировки Windows, может потребоваться более 60 секунд. Поэтому необходимо соответствующим образом увеличить значение ServicesPipeTimeout, чтобы дать всем зависимым службам достаточно времени для запуска.

Для получения дополнительных сведений щелкните следующий номер статьи, чтобы просмотреть статью в базе знаний Майкрософт:
839803 Служба диспетчера сеансов трассировки Windows не запустится и произойдет событие с ид 7000

Event Build pre & post to stop and restart Windows service

I’ve been experimenting with using build events to start and stop Windows service that are being built in my project. However for the pre & post builds fail with an error level 255. I’ve tried catching this with the pre-build with no luck.

4 Answers 4

The only problem is when you do a rebuild. Visual Studio cleans up the files before the pre-build event fires. This then off course fails because the service is still running. But regular builds work great. Hope this helps.

Try using the opening parenthese on the first line of your pre-build code

The conditional statement doesn’t require double-qoute («»)

It should be like

This is how I got it to work:

(this solution was a part of an enterprise software where some dll files are reused by another app)

Model is a project which is referenced in Service project and it is built before Service. Which is why we write these codes in Model’s Pre-Build Events:

Model Pre-Build Event:

  • creates a directory in output folder
  • finds the service by name
  • stops it
  • uninstalls it
  • exit 0 causes the build process to continue if error occurs here

Service Post-Build Event:

  • copy everything needed for the service to a different folder
  • installs service
  • starts service
  • visual studio will ask for elevated permission automatically

Windows Event Log Service not starting or is unavailable

Windows Event Log service maintains a set of event logs that the system, system components, and applications use to record events. The service exposes functions that allow programs to maintain and manage the event logs and perform operations on the logs, such as archiving and clearing. As such, administrators can maintain event logs and perform administrative tasks requiring administrator privileges.

Windows Event Log Service Not Starting or Running

For some unknown reason, if you find you are having difficulty starting the following, it is quite possible that one of the reasons could be that Windows Event Log Service is Not Running.

  • Task Scheduler
  • Windows Event Calendar
  • Messenger Sharing Folders

In such a scenario, you may get error messages like:

Event Log service is unavailable. Verify that the service is running

Windows could not start the Windows Event Log service on Local Computer

First, reboot your system and see if it helps. Sometimes a simple restart helps reinitialize this service. If the Windows Event Log shows as being started, re-start it from Services Manager.

To check if the Windows Event Log service is started or stopped, Run services.msc and hit Enter to open the Services Manager. Here, again right-click on Windows Event Log Service, check up its Properties.

Ensure that the Startup type is set on Automatic and that the services is Started; and that it runs in the Local Service account.

Also ensure in the Recovery tab, all three drop-down boxes, show the option as ‘Restart the Service’, in case of Failure. Reboot if required.

At times the Windows Event Log Service still will not start, and you may instead get the following error message:

System cannot find the file specified

In this case, open the following folder:

This logs folder contains Event Logs in .evtx format and can only be read with the Event Viewer. Give this logs folder Read-Write access rights and see if it helps.

You might also want to do the following.

Open Registry Editor and navigate to the following key:

Double-click ObjectName and ensure that its value is set at NT AUTHORITY\LocalService. If it is not, then change it.

If it still does not help, run the System File Checker and go through its logs.

Оцените статью