[英]How to keep Windows Service running after computer is restarted?
I have this Windows Service (using SqlDependency
) that sends me an e-mail everytime it is started and everytime a new row is inserted on my Sales table (the database has Service Broker
enabled).我有这个 Windows 服务(使用
SqlDependency
),它每次启动时都会向我发送一封电子邮件,并且每次在我的 Sales 表中插入新行(数据库启用了Service Broker
)。 I also write a log file to register when the service is started, the data is inserted to the table, if the e-mail was successfully sent and when the service is stoped.我还写了一个日志文件来注册服务启动时的数据,将数据插入到表中,如果电子邮件发送成功以及服务停止时。
Everytime it didn't work, I checked the services manager in Windows and it was marked as "Running".每次它不起作用时,我检查了 Windows 中的服务管理器,它被标记为“正在运行”。
I don't know if I need to configure something different in my code or in my service properties.我不知道是否需要在我的代码或服务属性中配置不同的东西。 Has anybody ever had this issue?
有没有人遇到过这个问题?
I modified my service and included a timer, so every minute passed it writes the time in my log text file.我修改了我的服务并包含了一个计时器,所以每过一分钟它都会在我的日志文本文件中写入时间。 After I restarted my PC, the log file continued to register the time every minute, but did not register the insert I made in my database table.
重新启动PC后,日志文件继续每分钟注册一次时间,但没有注册我在数据库表中所做的插入。
My guess is that the service might be losing the database connection when the PC is restarted, so the SqlDependency
cannot detect the changes.我的猜测是,当 PC 重新启动时,该服务可能会丢失数据库连接,因此
SqlDependency
无法检测到更改。 Does it make any sense?有什么意义吗?
Your service depends on SQL Server, but your service is probably starting before SQL Server has been started, or finished starting.您的服务取决于 SQL Server,但您的服务可能在 SQL Server 启动或完成启动之前启动。 This may be causing your
SqlDependency
to fail.这可能会导致您的
SqlDependency
失败。
You can mark your service as being dependent on SQL Server, which means:您可以将您的服务标记为依赖于 SQL Server,这意味着:
This can be achieved on the command-line with the sc
command (which will need to be run at an administrative command prompt).这可以使用
sc
命令在命令行上实现(需要在管理命令提示符下运行)。 If your SQL Server instance is named MSSQLSERVER
and your service is named MyService
the command would look like this:如果您的 SQL Server 实例名为
MSSQLSERVER
并且您的服务名为MyService
则命令将如下所示:
sc config MyService depend= MSSQLSERVER
Note: The space after =
and before MSSQLSERVER
matters.注意:
=
之后和MSSQLSERVER
之前的空格很重要。 The detailed syntax can be found on docs.microsoft.com .可以在docs.microsoft.com上找到详细的语法。
Once this command has run successfully, this is what you'll see when looking at the properties of your service in Control Panel > Administrative Tools > Services:此命令成功运行后,您将在“控制面板”>“管理工具”>“服务”中查看服务属性时看到以下内容:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.