我想在用 C++ 构建的 Windows 服务中定期调用一个方法。我正在调用 SvcMain() 中的方法。
int main(int argc, char* argv[])
{
// The Services to run have to be added in this table.
// It takes the Service Name and the name of the method to be called by SC Manager.
// Add any additional services for the process to this table.
SERVICE_TABLE_ENTRY ServiceTable[]= {{SVCNAME,(LPSERVICE_MAIN_FUNCTION)SvcMain},{NULL,NULL}};
// This call returns when the service has stopped.
// The process should simply terminate when the call returns.
StartServiceCtrlDispatcher(ServiceTable);
return 0;
}
void WINAPI SvcMain(DWORD argc, LPTSTR *argv)
{
ConnectToServer();
}
Q1。这会一直触发 ConnectToServer() 还是只触发一次?我只是不知道 win 服务是如何工作的。
Q2.我希望 ConnectToServer() 每 15 分钟触发一次。我该怎么做?
编辑:如何为该服务创建安装程序?
最佳答案
它将调用 SvcMain 一次。但是您没有在 SvcMain 中执行您应该执行的操作。 MSDN 上有一个关于 Writing a ServiceMain function 的很好的例子.
如果您复制该示例,您将编写代码以在 SvcInit 函数内(在 while(1)
循环内)调用 ConnectToServer。通过将 15 分钟指定为 WaitForSingleObject
调用中的超时值,您可以获得 15 分钟的调用延迟。
如果 ConnectToServer 是一个长时间运行的进程,您可能应该找到一种方法将其分解并在其中引入对 WaitForSingleObject
的更多调用,以便您的服务及时响应 Stop 请求。
关于c++ - Windows服务在C++中以一定的时间间隔运行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791046/