Run a (R) script as a service [server 2012R2]

windows-server-2012-r2windows-service

(complete windows noob here, I've been using Linux since a kid)

If I just run:

C:\Progra~1\R\R-3.4.0\bin\x64\Rscript.exe  C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\code_15.R

in the windows server DOS terminal as an administrator, it works fine.

Now I need to run this script as a service (policy of the place that pays me food);

I looked a bit on the internet and put this in the windows server DOS terminal:

sc create myRScript5 binPath= "cmd.exe /c C:\Progra~1\R\R-3.4.0\bin\x64\Rscript.exe  C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\code_15.R" DisplayName= "My R script 5" 

The service is correctly displayed in the list. I right click and press 'start'.
I get:

Error 1053: The Service did not respond to the start request 

I have also tried some more or less inspired variants such as:

sc create myRScript3 binPath= "C:\Progra~1\R\R-3.4.0\bin\x64\Rscript.exe \"C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\progtest.R\"" DisplayName= "My R script 3" 

I must be doing something stupid but I do not know what. FWIW here is code_15.R

setwd("C:/Users/NPX9sx9000010190CAL/Desktop/el_leo")


library(doSNOW)

print('boom')
set.seed(123)
x = runif(10)
write.table(x, 'yahoo.txt')

EDIT

Some I am trying SqlACID solution (probably botching it somewhere).

I installed srvany.

I created a file

C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\rrr.bat 

that contains:

C:\Progra~1\R\R-3.4.0\bin\x64\Rscript.exe  C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\code_15.R

I start the windows terminal as administrator and ran:

sc create "MyFirstService" binPath= "C:\Temp\SrvAny.exe" start= auto

I get

[SC] CreateService SUCCESS

from the windows terminal. I start RegEdit and found

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyFirstService

I created a key Parameter

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyFirstService\Parameters

Inside it, I created a new string Application of type REG_SZ and with value_data:

C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\rrr.bat

Then, I go to Services, find MyFirstService and right click Run;

I got

Error 2: The system could not find the file specified

Best Answer

Services are expected to respond to start/stop requests in very specific manners, and cmd.exe is not able to do that; there used to be a "service wrapper" that would encapsulate a generic executable as a service, it was provided with the Windows Server Resource Kit, look for SRVANY.EXE, I have no idea if it would function with newer OS's or whether there are alternatives, but it's worth a try.

OP resolved the issue by using a scheduled task running a batch file rather than a service.

OP here: A collegue contributed the following:

schtasks /create /sc ONCE /tn OP /tr C:\Users\NPX9sx9000010190CAL\Desktop\el_leo\R.bat /st 09:35