Как установить программу в качестве службы
Наверняка, многие сталкивались с ситуацией, когда есть необходимость запускать программу до входа пользователя в систему, но в установщике программы нет опции «Установить в качестве службы».
Установка программы в качестве службы
Первые 4 пункта понадобятся лишь в windows 8.1
1 Вызовите боковую панель Windows 8.1. Для этого можно использовать комбинацию клавиш WIN+C.
2 Выберите Поиск:
3 В поле поиска введите командная строка. В списке появится позиция Командная строка с системной иконкой.
Нажмите по ней правой кнопкой мыши:
4 Выберите Запуск от имени администратора:
5 Нажмите Да:
6 В командной строке введите путь к программе, которую вы хотите установить в качестве службы, с ключом /installservice и нажать ENTER. Путь необходимо взять в кавычки.
После нажатия на ENTER ответьте «Да» на запрос службы контроля учётных записей:
7 Если программа запросит учётные данные для запуска, как в нашем примере, введите реквизиты учётной записи администратора и нажмите ОК:
Далее, программа, которую вы установили в качестве службы, сообщит вам об успешной установке службы.
У каждой программы это окно будет разным
Зайдите в службы (Выполнить — services.mcs — ENTER) и проверьте, что в списке присутствует только что установленная служба:
Удаление службы
Процедура удаления службы схожа с установкой. Отличие лишь в том, что после пути к программе нужно указать ключ /uninstallservice.
.NET console application as Windows service
I have console application and would like to run it as Windows service. VS2010 has project template which allow to attach console project and build Windows service. I would like to not add separated service project and if possible integrate service code into console application to keep console application as one project which could run as console application or as windows service if run for example from command line using switches.
Maybe someone could suggest class library or code snippet which could quickly and easily transform c# console application to service?
10 Answers 10
I usually use the following techinque to run the same app as a console application or as a service:
Environment.UserInteractive is normally true for console app and false for a service. Techically, it is possible to run a service in user-interactive mode, so you could check a command-line switch instead.
I’ve had great success with TopShelf.
TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.
From the Package Manager Console (Nuget):
Refer to the code samples to get started.
TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:
You don’t need to hook up a ServiceInstaller and all that — TopShelf does it all for you.
So here’s the complete walkthrough:
- Create new Console Application project (e.g. MyService)
- Add two library references: System.ServiceProcess and System.Configuration.Install
- Add the three files printed below
- Build the project and run «InstallUtil.exe c:\path\to\MyService.exe»
- Now you should see MyService on the service list (run services.msc)
*InstallUtil.exe can be usually found here: C:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe
Program.cs
MyService.cs
MyServiceInstaller.cs
Here is a newer way of how to turn a Console Application to a Windows Service as a Worker Service based on the latest .Net Core 3.1.
If you create a Worker Service from Visual Studio 2019 it will give you almost everything you need for creating a Windows Service out of the box, which is also what you need to change to the console application in order to convert it to a Windows Service.
Here are the changes you need to do:
Install the following NuGet packages
Change Program.cs to have an implementation like below:
and add Worker.cs where you will put the code which will be run by the service operations:
When everything is ready, and the application has built successfully, you can use sc.exe to install your console application exe as a Windows Service with the following command:
I hear your point at wanting one assembly to stop repeated code but, It would be simplest and reduce code repetition and make it easier to reuse your code in other ways in future if. you to break it into 3 assemblies.
- One library assembly that does all the work. Then have two very very slim/simple projects:
- one which is the commandline
- one which is the windows service.
Firstly I embed the console application solution into the windows service solution and reference it.
Then I make the console application Program class public
I then create two functions within the console application
Then within the windows service itself I instantiate the Program and call the Start and Stop functions added within the OnStart and OnStop. See below
This approach can also be used for a windows application / windows service hybrid
And it will appear int the service list. I do not know, whether that works correctly though. A service usually has to listen to several events.
There are several service wrapper though, that can run any application as a real service. For Example Microsofts SrvAny from the Win2003 Resource Kit
Maybe you should define what you need, as far as I know, you can’t run your app as Console or Service with command line, at the same time. Remember that the service is installed and you have to start it in Services Manager, you can create a new application wich starts the service or starts a new process running your console app. But as you wrote
«keep console application as one project»
Once, I was in your position, turning a console application into a service. First you need the template, in case you are working with VS Express Edition. Here is a link where you can have your first steps: C# Windows Service, this was very helpful for me. Then using that template, add your code to the desired events of the service.
To improve you service, there’s another thing you can do, but this is not quick and/or easily, is using appdomains, and creating dlls to load/unload. In one you can start a new process with the console app, and in another dll you can just put the functionality the service has to do.
You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.
As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can’t directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.
It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.
The Console stub can very useful for debugging service behaviour but should not be used in a «productionized» environment which, after all, is the purpose of creating a service.
I haven’t read it fully but this article seems to pint in the right direction.
Run batch file as a Windows service
In order to run one application, a batch file has to be kicked off (which does things like start Jetty, display live logs, etc). The application will work only if this batch file is running. I am hence forced to have this batch file running and not logout from the Windows server.
Can this batch file be run as a service? I am experimenting with one of the suggestions from a similar question.
8 Answers 8
NSSM is totally free and hyper-easy, running command prompt / terminal as administrator:
then a dialog will appear so you can choose where is the file you want to run.
Why not simply set it up as a Scheduled Task that is scheduled to run at start up?
There’s a built in windows cmd to do this: sc create. Not as fancy as nssm, but you don’t have to download an additional piece of software.
- start=demand means you must start the service yourself
- whitespace is required after =
- I did encounter an error on service start that the service did not respond in a timely manner, but it was clear the service had run the .bat successfully. Haven’t dug into this yet but this thread experienced the same thing and solved it using nssm to install the service.
No need for extra software. Use the task scheduler -> create task -> hidden. The checkbox for hidden is in the bottom left corner. Set the task to trigger on login (or whatever condition you like) and choose the task in the actions tab. Running it hidden ensures that the task runs silently in the background like a service.
Note that you must also set the program to run «whether the user is logged in or not» or the program will still run in the foreground.
On Windows 2019 Server, you can run a Minecraft java server with these commands:
sc create minecraft-server DisplayName= «minecraft-server» binpath= «cmd.exe /C C:\Users\Administrator\Desktop\rungui1151.lnk» type= own start= auto
The .lnk file is a standard windows shortcut to a batch file.
— .bat file begins —
java -Xmx40960M -Xms40960M -d64 -jar minecraft_server.1.15.1.jar
All this because:
service does not know how to start in a folder,
cmd.exe does not know how to start in a folder
Starting the service will produce «timely manner» error, but the log file reveals the server is running.
If you need to shut down the server, just go into task manager and find the server java in background processes and end it, or terminate the server from in the game using the /stop command, or for other programs/servers, use the methods relevant to the server.
As Doug Currie says use RunAsService.
From my past experience you must remember that the Service you generate will
- have a completely different set of environment variables
- have to be carefully inspected for rights/permissions issues
- might cause havoc if it opens dialogs asking for any kind of input
not sure if the last one still applies . it was one big night mare in a project I worked on some time ago.
While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.
I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.
There’s also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).
Install NSSM and run the .bat file as a windows service. Works as expected
Create Windows service from executable
Is there any quick way to, given an executable file, create a Windows service that, when started, launches it?
10 Answers 10
To create a Windows Service from an executable, you can use sc.exe :
You must have quotation marks around the actual exe path, and a space after the binPath= .
Note that it will not work for just any executable: the executable must be a Windows Service (i.e. implement ServiceMain). When registering a non-service executable as a service, you’ll get the following error upon trying to start the service:
Error 1053: The service did not respond to the start or control request in a timely fashion.
There are tools that can create a Windows Service from arbitrary, non-service executables, see the other answers for examples of such tools.
Use NSSM( the non-Sucking Service Manager ) to run a .BAT or any .EXE file as a service.
- Step 1: Download NSSM
- Step 2: Install your sevice with nssm.exe install [serviceName]
- Step 3: This will open a GUI which you will use to locate your executable
Extending (Kevin Tong) answer.
Step 1: Download & Unzip nssm-2.24.zip
Step 2: From command line type:
C:\> nssm.exe install [servicename]
it will open GUI as below (the example is UT2003 server), then simply browse it to: yourapplication.exe
Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.
Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run
will install the service. stdout and stderr are all logged. For more info, take a look at the project website.
A working configuration file is very simple, as demonstrated below. But it also has many useful features such as and
these extras prove useful.. need to be executed as an administrator
If your service name has any spaces, enclose in «quotes».
I’ve tested a good product for that: AlwaysUp. Not free but they have a 30 days trial period so you can give it a try.
Same as Sergii Pozharov’s answer, but with a PowerShell cmdlet:
See New-Service for more customization.
This will only work for executables that already implement the Windows Services API.
You can check out my small free utility for service create\edit\delete operations. Here is create example:
Go to Service -> Modify -> Create
Executable file (google drive): [Download]
Probably all your answers are better, but — just to be complete on the choice of options — I wanted to remind about old, similar method used for years:
SrvAny (installed by InstSrv)
I created the cross-platform Service Manager software a few years back so that I could start PHP and other scripting languages as system services on Windows, Mac, and Linux OSes:
Service Manager is a set of precompiled binaries that install and manage a system service on the target OS using nearly identical command-line options (source code also available). Each platform does have subtle differences but the core features are mostly normalized.
If the child process dies, Service Manager automatically restarts it.
Processes that are started with Service Manager should periodically watch for two notification files to handle restart and reload requests but they don’t necessarily have to do that. Service Manager will force restart the child process if it doesn’t respond in a timely fashion to controlled restart/reload requests.